diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/clients/java/src/test/java/com/thoughtworks/selenium/SeleneseTestCase.java b/clients/java/src/test/java/com/thoughtworks/selenium/SeleneseTestCase.java index 27b3e154..314aff6e 100644 --- a/clients/java/src/test/java/com/thoughtworks/selenium/SeleneseTestCase.java +++ b/clients/java/src/test/java/com/thoughtworks/selenium/SeleneseTestCase.java @@ -1,215 +1,214 @@ /* * Copyright 2004 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.thoughtworks.selenium; import junit.framework.*; import org.openqa.selenium.server.*; /** * @author Nelson Sproul ([email protected]) Mar 13-06 */ public class SeleneseTestCase extends TestCase { protected Selenium selenium; protected static StringBuffer verificationErrors = new StringBuffer(); protected void setUp() throws Exception { super.setUp(); this.setUp(null); } protected void setUp(String url) throws Exception { super.setUp(); if (url==null) { url = "http://localhost:" + SeleniumServer.DEFAULT_PORT; } selenium = new DefaultSelenium("localhost", SeleniumServer.DEFAULT_PORT, "*iexplore", url); selenium.start(); } public void verifyTrue(boolean b) { try { assertTrue(b); } catch (Exception e) { verificationErrors.append(e); } } public void verifyFalse(boolean b) { try { assertFalse(b); } catch (Exception e) { verificationErrors.append(e); } } protected String getText() { return selenium.getEval("this.page().bodyText()"); } public static void verifyEquals(Object s1, Object s2) { try { assertEquals(s1, s2); } catch (Exception e) { verificationErrors.append(e); } } public static void assertEquals(Object s1, Object s2) { if (s1 instanceof String && s2 instanceof String) { assertEquals((String)s1, (String)s2); } else { if (s1 instanceof String[] && s2 instanceof String[]) { String[] sa1 = (String[]) s1; String[] sa2 = (String[]) s2; if (sa1.length!=sa2.length) { throw new AssertionFailedError("Expected " + sa1 + " but saw " + sa2); } } Assert.assertEquals(s1, s2); } } public static void assertEquals(String s1, String s2) { assertTrue(seleniumEquals(s1, s2)); } public static boolean seleniumEquals(String s1, String s2) { if (s2.startsWith("regexp:")) { String tmp = s2; s2 = s1; s1 = tmp; } if (s1.startsWith("regexp:")) { String s1regexp = s1.replaceFirst("regexp:", ".*") + ".*"; if (!s2.matches(s1regexp)) { System.out.println("expected " + s2 + " to match regexp " + s1); return false; } return true; } if (s1.startsWith("exact:")) { String s1exact = s1.replaceFirst("exact:", ""); if (!s1exact.equals(s2)) { System.out.println("expected " + s2 + " to match " + s1); return false; } return true; } String s1glob = s1.replaceFirst("glob:", ".*") .replaceAll("\\*", ".*") - .replaceAll("[\\]\\[\\$\\(\\).]", "\\\\$1") - .replaceAll("\\.", "\\\\.") + .replaceAll("([\\]\\[\\$\\(\\).])", "\\\\$1") .replaceAll("\\?", ".") + ".*"; if (!s2.matches(s1glob)) { System.out.println("expected " + s2 + " to match glob " + s1 + " (had transformed the glob into regexp:" + s1glob); return false; } return true; } public static boolean seleniumEquals(Object s1, Object s2) { if (s1 instanceof String && s2 instanceof String) { return seleniumEquals((String)s1, (String)s2); } return s1.equals(s2); } public static void assertEquals(String[] s1, String[] s2) { String comparisonDumpIfNotEqual = verifyEqualsAndReturnComparisonDumpIfNot(s1, s2); if (comparisonDumpIfNotEqual!=null) { throw new AssertionFailedError(comparisonDumpIfNotEqual); } } public static void verifyEquals(String[] s1, String[] s2) { String comparisonDumpIfNotEqual = verifyEqualsAndReturnComparisonDumpIfNot(s1, s2); if (comparisonDumpIfNotEqual!=null) { verificationErrors.append(comparisonDumpIfNotEqual); } } private static String verifyEqualsAndReturnComparisonDumpIfNot(String[] s1, String[] s2) { boolean misMatch = false; if (s1.length != s2.length) { misMatch = true; } for (int j = 0; j < s1.length; j++) { if (!s1[j].equals(s2[j])) { misMatch = true; break; } } if (misMatch) { return "Expected " + stringArrayToString(s1) + " but saw " + stringArrayToString(s2); } return null; } private static String stringArrayToString(String[] sa) { StringBuffer sb = new StringBuffer("{"); for (int j = 0; j < sa.length; j++) { sb.append(" ") .append("\"") .append(sa[j]) .append("\""); } sb.append(" }"); return sb.toString(); } public static void verifyNotEquals(String s1, String s2) { try { assertNotEquals(s1, s2); } catch (Exception e) { verificationErrors.append(e); } } public static void assertNotEquals(Object obj1, Object obj2) { if (obj1.equals(obj2)) { fail("did not expect values to be equal (" + obj1.toString() + ")"); } } protected void pause(int millisecs) { try { Thread.sleep(millisecs); } catch (InterruptedException e) { } } protected String quote(String value) { return "'" + value.replaceAll("'", "\\'") + "'"; } public void checkForVerificationErrors() { assertEquals("", verificationErrors.toString()); } protected void tearDown() throws Exception { selenium.stop(); } }
true
true
public static boolean seleniumEquals(String s1, String s2) { if (s2.startsWith("regexp:")) { String tmp = s2; s2 = s1; s1 = tmp; } if (s1.startsWith("regexp:")) { String s1regexp = s1.replaceFirst("regexp:", ".*") + ".*"; if (!s2.matches(s1regexp)) { System.out.println("expected " + s2 + " to match regexp " + s1); return false; } return true; } if (s1.startsWith("exact:")) { String s1exact = s1.replaceFirst("exact:", ""); if (!s1exact.equals(s2)) { System.out.println("expected " + s2 + " to match " + s1); return false; } return true; } String s1glob = s1.replaceFirst("glob:", ".*") .replaceAll("\\*", ".*") .replaceAll("[\\]\\[\\$\\(\\).]", "\\\\$1") .replaceAll("\\.", "\\\\.") .replaceAll("\\?", ".") + ".*"; if (!s2.matches(s1glob)) { System.out.println("expected " + s2 + " to match glob " + s1 + " (had transformed the glob into regexp:" + s1glob); return false; } return true; }
public static boolean seleniumEquals(String s1, String s2) { if (s2.startsWith("regexp:")) { String tmp = s2; s2 = s1; s1 = tmp; } if (s1.startsWith("regexp:")) { String s1regexp = s1.replaceFirst("regexp:", ".*") + ".*"; if (!s2.matches(s1regexp)) { System.out.println("expected " + s2 + " to match regexp " + s1); return false; } return true; } if (s1.startsWith("exact:")) { String s1exact = s1.replaceFirst("exact:", ""); if (!s1exact.equals(s2)) { System.out.println("expected " + s2 + " to match " + s1); return false; } return true; } String s1glob = s1.replaceFirst("glob:", ".*") .replaceAll("\\*", ".*") .replaceAll("([\\]\\[\\$\\(\\).])", "\\\\$1") .replaceAll("\\?", ".") + ".*"; if (!s2.matches(s1glob)) { System.out.println("expected " + s2 + " to match glob " + s1 + " (had transformed the glob into regexp:" + s1glob); return false; } return true; }
diff --git a/dexlib/src/main/java/org/jf/dexlib/Util/Utf8Utils.java b/dexlib/src/main/java/org/jf/dexlib/Util/Utf8Utils.java index c2ccd26..0011bc5 100644 --- a/dexlib/src/main/java/org/jf/dexlib/Util/Utf8Utils.java +++ b/dexlib/src/main/java/org/jf/dexlib/Util/Utf8Utils.java @@ -1,260 +1,260 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * As per the Apache license requirements, this file has been modified * from its original state. * * Such modifications are Copyright (C) 2010 Ben Gruver, and are released * under the original license */ package org.jf.dexlib.Util; import java.io.IOException; import java.io.Writer; /** * Constants of type <code>CONSTANT_Utf8_info</code>. */ public final class Utf8Utils { /** * Converts a string into its Java-style UTF-8 form. Java-style UTF-8 * differs from normal UTF-8 in the handling of character '\0' and * surrogate pairs. * * @param string non-null; the string to convert * @return non-null; the UTF-8 bytes for it */ public static byte[] stringToUtf8Bytes(String string) { int len = string.length(); byte[] bytes = new byte[len * 3]; // Avoid having to reallocate. int outAt = 0; for (int i = 0; i < len; i++) { char c = string.charAt(i); if ((c != 0) && (c < 0x80)) { bytes[outAt] = (byte) c; outAt++; } else if (c < 0x800) { bytes[outAt] = (byte) (((c >> 6) & 0x1f) | 0xc0); bytes[outAt + 1] = (byte) ((c & 0x3f) | 0x80); outAt += 2; } else { bytes[outAt] = (byte) (((c >> 12) & 0x0f) | 0xe0); bytes[outAt + 1] = (byte) (((c >> 6) & 0x3f) | 0x80); bytes[outAt + 2] = (byte) ((c & 0x3f) | 0x80); outAt += 3; } } byte[] result = new byte[outAt]; System.arraycopy(bytes, 0, result, 0, outAt); return result; } private static char[] tempBuffer = null; /** * Converts an array of UTF-8 bytes into a string. * * This method uses a global buffer to avoid having to allocate one every time, so it is *not* thread-safe * * @param bytes non-null; the bytes to convert * @param start the start index of the utf8 string to convert * @param length the length of the utf8 string to convert, not including any null-terminator that might be present * @return non-null; the converted string */ public static String utf8BytesToString(byte[] bytes, int start, int length) { if (tempBuffer == null || tempBuffer.length < length) { tempBuffer = new char[length]; } char[] chars = tempBuffer; int outAt = 0; for (int at = start; length > 0; /*at*/) { int v0 = bytes[at] & 0xFF; char out; switch (v0 >> 4) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: { // 0XXXXXXX -- single-byte encoding length--; if (v0 == 0) { // A single zero byte is illegal. return throwBadUtf8(v0, at); } out = (char) v0; at++; break; } case 0x0c: case 0x0d: { // 110XXXXX -- two-byte encoding length -= 2; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int value = ((v0 & 0x1f) << 6) | (v1 & 0x3f); if ((value != 0) && (value < 0x80)) { /* * This should have been represented with * one-byte encoding. */ return throwBadUtf8(v1, at + 1); } out = (char) value; at += 2; break; } case 0x0e: { // 1110XXXX -- three-byte encoding length -= 3; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int v2 = bytes[at + 2] & 0xFF; - if ((v1 & 0xc0) != 0x80) { + if ((v2 & 0xc0) != 0x80) { return throwBadUtf8(v2, at + 2); } int value = ((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) | (v2 & 0x3f); if (value < 0x800) { /* * This should have been represented with one- or * two-byte encoding. */ return throwBadUtf8(v2, at + 2); } out = (char) value; at += 3; break; } default: { // 10XXXXXX, 1111XXXX -- illegal return throwBadUtf8(v0, at); } } chars[outAt] = out; outAt++; } return new String(chars, 0, outAt); } /** * Helper for {@link #utf8BytesToString}, which throws the right * exception for a bogus utf-8 byte. * * @param value the byte value * @param offset the file offset * @return never * @throws IllegalArgumentException always thrown */ private static String throwBadUtf8(int value, int offset) { throw new IllegalArgumentException("bad utf-8 byte " + Hex.u1(value) + " at offset " + Hex.u4(offset)); } public static void writeEscapedChar(Writer writer, char c) throws IOException { if ((c >= ' ') && (c < 0x7f)) { if ((c == '\'') || (c == '\"') || (c == '\\')) { writer.write('\\'); } writer.write(c); return; } else if (c <= 0x7f) { switch (c) { case '\n': writer.write("\\n"); return; case '\r': writer.write("\\r"); return; case '\t': writer.write("\\t"); return; } } writer.write("\\u"); writer.write(Character.forDigit(c >> 12, 16)); writer.write(Character.forDigit((c >> 8) & 0x0f, 16)); writer.write(Character.forDigit((c >> 4) & 0x0f, 16)); writer.write(Character.forDigit(c & 0x0f, 16)); } public static void writeEscapedString(Writer writer, String value) throws IOException { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if ((c >= ' ') && (c < 0x7f)) { if ((c == '\'') || (c == '\"') || (c == '\\')) { writer.write('\\'); } writer.write(c); continue; } else if (c <= 0x7f) { switch (c) { case '\n': writer.write("\\n"); continue; case '\r': writer.write("\\r"); continue; case '\t': writer.write("\\t"); continue; } } writer.write("\\u"); writer.write(Character.forDigit(c >> 12, 16)); writer.write(Character.forDigit((c >> 8) & 0x0f, 16)); writer.write(Character.forDigit((c >> 4) & 0x0f, 16)); writer.write(Character.forDigit(c & 0x0f, 16)); } } public static String escapeString(String value) { int len = value.length(); StringBuilder sb = new StringBuilder(len * 3 / 2); for (int i = 0; i < len; i++) { char c = value.charAt(i); if ((c >= ' ') && (c < 0x7f)) { if ((c == '\'') || (c == '\"') || (c == '\\')) { sb.append('\\'); } sb.append(c); continue; } else if (c <= 0x7f) { switch (c) { case '\n': sb.append("\\n"); continue; case '\r': sb.append("\\r"); continue; case '\t': sb.append("\\t"); continue; } } sb.append("\\u"); sb.append(Character.forDigit(c >> 12, 16)); sb.append(Character.forDigit((c >> 8) & 0x0f, 16)); sb.append(Character.forDigit((c >> 4) & 0x0f, 16)); sb.append(Character.forDigit(c & 0x0f, 16)); } return sb.toString(); } }
true
true
public static String utf8BytesToString(byte[] bytes, int start, int length) { if (tempBuffer == null || tempBuffer.length < length) { tempBuffer = new char[length]; } char[] chars = tempBuffer; int outAt = 0; for (int at = start; length > 0; /*at*/) { int v0 = bytes[at] & 0xFF; char out; switch (v0 >> 4) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: { // 0XXXXXXX -- single-byte encoding length--; if (v0 == 0) { // A single zero byte is illegal. return throwBadUtf8(v0, at); } out = (char) v0; at++; break; } case 0x0c: case 0x0d: { // 110XXXXX -- two-byte encoding length -= 2; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int value = ((v0 & 0x1f) << 6) | (v1 & 0x3f); if ((value != 0) && (value < 0x80)) { /* * This should have been represented with * one-byte encoding. */ return throwBadUtf8(v1, at + 1); } out = (char) value; at += 2; break; } case 0x0e: { // 1110XXXX -- three-byte encoding length -= 3; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int v2 = bytes[at + 2] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v2, at + 2); } int value = ((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) | (v2 & 0x3f); if (value < 0x800) { /* * This should have been represented with one- or * two-byte encoding. */ return throwBadUtf8(v2, at + 2); } out = (char) value; at += 3; break; } default: { // 10XXXXXX, 1111XXXX -- illegal return throwBadUtf8(v0, at); } } chars[outAt] = out; outAt++; } return new String(chars, 0, outAt); }
public static String utf8BytesToString(byte[] bytes, int start, int length) { if (tempBuffer == null || tempBuffer.length < length) { tempBuffer = new char[length]; } char[] chars = tempBuffer; int outAt = 0; for (int at = start; length > 0; /*at*/) { int v0 = bytes[at] & 0xFF; char out; switch (v0 >> 4) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: { // 0XXXXXXX -- single-byte encoding length--; if (v0 == 0) { // A single zero byte is illegal. return throwBadUtf8(v0, at); } out = (char) v0; at++; break; } case 0x0c: case 0x0d: { // 110XXXXX -- two-byte encoding length -= 2; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int value = ((v0 & 0x1f) << 6) | (v1 & 0x3f); if ((value != 0) && (value < 0x80)) { /* * This should have been represented with * one-byte encoding. */ return throwBadUtf8(v1, at + 1); } out = (char) value; at += 2; break; } case 0x0e: { // 1110XXXX -- three-byte encoding length -= 3; if (length < 0) { return throwBadUtf8(v0, at); } int v1 = bytes[at + 1] & 0xFF; if ((v1 & 0xc0) != 0x80) { return throwBadUtf8(v1, at + 1); } int v2 = bytes[at + 2] & 0xFF; if ((v2 & 0xc0) != 0x80) { return throwBadUtf8(v2, at + 2); } int value = ((v0 & 0x0f) << 12) | ((v1 & 0x3f) << 6) | (v2 & 0x3f); if (value < 0x800) { /* * This should have been represented with one- or * two-byte encoding. */ return throwBadUtf8(v2, at + 2); } out = (char) value; at += 3; break; } default: { // 10XXXXXX, 1111XXXX -- illegal return throwBadUtf8(v0, at); } } chars[outAt] = out; outAt++; } return new String(chars, 0, outAt); }
diff --git a/nuxeo-webdav/src/main/java/org/nuxeo/ecm/webdav/resource/UnknownResource.java b/nuxeo-webdav/src/main/java/org/nuxeo/ecm/webdav/resource/UnknownResource.java index 6a08e2d..5d288b1 100644 --- a/nuxeo-webdav/src/main/java/org/nuxeo/ecm/webdav/resource/UnknownResource.java +++ b/nuxeo-webdav/src/main/java/org/nuxeo/ecm/webdav/resource/UnknownResource.java @@ -1,152 +1,153 @@ /* * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id$ */ package org.nuxeo.ecm.webdav.resource; import net.java.dev.webdav.jaxrs.methods.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.*; import org.nuxeo.ecm.core.api.impl.DocumentModelImpl; import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob; import org.nuxeo.ecm.webdav.Util; import org.nuxeo.ecm.webdav.backend.WebDavBackend; import org.nuxeo.runtime.services.streaming.InputStreamSource; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.HEAD; import javax.ws.rs.PUT; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; /** * Resource for an unknown (ie non-existing) object. * Used so that PUT / MKCOL requests can actually created a document / folder. * Other requests will end up with a 404 error. */ public class UnknownResource extends AbstractResource { private static final Log log = LogFactory.getLog(UnknownResource.class); protected WebDavBackend backend; public UnknownResource(String path, HttpServletRequest request, WebDavBackend backend) throws Exception { super(path, request); this.backend = backend; } /** * PUT over a non-existing resource: create a new file resource. */ @PUT public Response put() throws Exception { // Special case: ignore magic MacOS files. // Actually, we shouldn't do this. This breaks drag'n'drop of files downloaded from the // Internet (Finder fails with error "Unable to quarantine" in the logs). // TODO: find a better way. /* if (name.startsWith("._")) { Util.endTransaction(); // Not sure if it's the right error code. throw new WebApplicationException(409); } */ ensureParentExists(); Blob content = new StreamingBlob(new InputStreamSource(request.getInputStream())); - if (content.getLength() > 0) { + // note that content.getLentgh from an input stream source always return -1 + if (request.getContentLength() > 0) { String contentType = request.getContentType(); if (contentType == null) { contentType = "application/octet-stream"; } content.setMimeType(contentType); - content.setFilename(name); - backend.createFile(parentPath, name, content); + content.setFilename(name); + backend.createFile(parentPath, name, content); } else { backend.createFile(parentPath, name); } backend.saveChanges(); return Response.created(new URI(request.getRequestURI())).build(); } /** * MKCOL over a non-existing resource: create a new folder resource. */ @MKCOL public Response mkcol() throws Exception { ensureParentExists(); //We really need this? InputStreamSource iss = new InputStreamSource(request.getInputStream()); if (iss.getString().length() > 0) { return Response.status(415).build(); } backend.createFolder(parentPath, name); backend.saveChanges(); return Response.created(new URI(request.getRequestURI())).build(); } // All these methods should raise an error 404 @DELETE public Response delete() { return Response.status(404).build(); } @COPY public Response copy() { return Response.status(404).build(); } @MOVE public Response move() { return Response.status(404).build(); } @PROPFIND public Response propfind() { return Response.status(404).build(); } @PROPPATCH public Response proppatch() { return Response.status(404).build(); } @HEAD public Response head() { return Response.status(404).build(); } // Utility private void ensureParentExists() throws Exception { if (!backend.exists(parentPath)) { throw new WebApplicationException(409); } } }
false
true
public Response put() throws Exception { // Special case: ignore magic MacOS files. // Actually, we shouldn't do this. This breaks drag'n'drop of files downloaded from the // Internet (Finder fails with error "Unable to quarantine" in the logs). // TODO: find a better way. /* if (name.startsWith("._")) { Util.endTransaction(); // Not sure if it's the right error code. throw new WebApplicationException(409); } */ ensureParentExists(); Blob content = new StreamingBlob(new InputStreamSource(request.getInputStream())); if (content.getLength() > 0) { String contentType = request.getContentType(); if (contentType == null) { contentType = "application/octet-stream"; } content.setMimeType(contentType); content.setFilename(name); backend.createFile(parentPath, name, content); } else { backend.createFile(parentPath, name); } backend.saveChanges(); return Response.created(new URI(request.getRequestURI())).build(); }
public Response put() throws Exception { // Special case: ignore magic MacOS files. // Actually, we shouldn't do this. This breaks drag'n'drop of files downloaded from the // Internet (Finder fails with error "Unable to quarantine" in the logs). // TODO: find a better way. /* if (name.startsWith("._")) { Util.endTransaction(); // Not sure if it's the right error code. throw new WebApplicationException(409); } */ ensureParentExists(); Blob content = new StreamingBlob(new InputStreamSource(request.getInputStream())); // note that content.getLentgh from an input stream source always return -1 if (request.getContentLength() > 0) { String contentType = request.getContentType(); if (contentType == null) { contentType = "application/octet-stream"; } content.setMimeType(contentType); content.setFilename(name); backend.createFile(parentPath, name, content); } else { backend.createFile(parentPath, name); } backend.saveChanges(); return Response.created(new URI(request.getRequestURI())).build(); }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java index cdd12667..da6dcc8d 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java @@ -1,359 +1,359 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.statusbar.phone; import static com.android.internal.util.cm.QSConstants.TILES_DEFAULT; import static com.android.internal.util.cm.QSConstants.TILE_AIRPLANE; import static com.android.internal.util.cm.QSConstants.TILE_AUTOROTATE; import static com.android.internal.util.cm.QSConstants.TILE_BAMCONTROL; import static com.android.internal.util.cm.QSConstants.TILE_BATTERY; import static com.android.internal.util.cm.QSConstants.TILE_BLUETOOTH; import static com.android.internal.util.cm.QSConstants.TILE_BRIGHTNESS; import static com.android.internal.util.cm.QSConstants.TILE_DELIMITER; import static com.android.internal.util.cm.QSConstants.TILE_GPS; import static com.android.internal.util.cm.QSConstants.TILE_HOLOBAM; import static com.android.internal.util.cm.QSConstants.TILE_LOCKSCREEN; import static com.android.internal.util.cm.QSConstants.TILE_MUSIC; import static com.android.internal.util.cm.QSConstants.TILE_MOBILEDATA; import static com.android.internal.util.cm.QSConstants.TILE_NETWORKMODE; import static com.android.internal.util.cm.QSConstants.TILE_NFC; import static com.android.internal.util.cm.QSConstants.TILE_RINGER; import static com.android.internal.util.cm.QSConstants.TILE_SCREENTIMEOUT; import static com.android.internal.util.cm.QSConstants.TILE_SETTINGS; import static com.android.internal.util.cm.QSConstants.TILE_SLEEP; import static com.android.internal.util.cm.QSConstants.TILE_SYNC; import static com.android.internal.util.cm.QSConstants.TILE_TORCH; import static com.android.internal.util.cm.QSConstants.TILE_USER; import static com.android.internal.util.cm.QSConstants.TILE_VOLUME; import static com.android.internal.util.cm.QSConstants.TILE_WIFI; import static com.android.internal.util.cm.QSConstants.TILE_WIFIAP; import static com.android.internal.util.cm.QSConstants.TILE_DESKTOPMODE; import static com.android.internal.util.cm.QSConstants.TILE_HYBRID; import static com.android.internal.util.cm.QSConstants.TILE_REBOOT; import static com.android.internal.util.cm.QSUtils.deviceSupportsBluetooth; import static com.android.internal.util.cm.QSUtils.deviceSupportsMobileData; import static com.android.internal.util.cm.QSUtils.deviceSupportsUsbTether; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.net.Uri; import android.os.Handler; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import com.android.systemui.statusbar.BaseStatusBar; import com.android.systemui.quicksettings.AirplaneModeTile; import com.android.systemui.quicksettings.AlarmTile; import com.android.systemui.quicksettings.AutoRotateTile; import com.android.systemui.quicksettings.BamcontrolTile; import com.android.systemui.quicksettings.BatteryTile; import com.android.systemui.quicksettings.BluetoothTile; import com.android.systemui.quicksettings.BrightnessTile; import com.android.systemui.quicksettings.BugReportTile; import com.android.systemui.quicksettings.GPSTile; import com.android.systemui.quicksettings.HolobamTile; import com.android.systemui.quicksettings.InputMethodTile; import com.android.systemui.quicksettings.MobileNetworkTile; import com.android.systemui.quicksettings.MobileNetworkTypeTile; import com.android.systemui.quicksettings.NfcTile; import com.android.systemui.quicksettings.MusicTile; import com.android.systemui.quicksettings.PreferencesTile; import com.android.systemui.quicksettings.QuickSettingsTile; import com.android.systemui.quicksettings.RingerModeTile; import com.android.systemui.quicksettings.ScreenTimeoutTile; import com.android.systemui.quicksettings.SleepScreenTile; import com.android.systemui.quicksettings.SyncTile; import com.android.systemui.quicksettings.ToggleLockscreenTile; import com.android.systemui.quicksettings.TorchTile; import com.android.systemui.quicksettings.UsbTetherTile; import com.android.systemui.quicksettings.UserTile; import com.android.systemui.quicksettings.VolumeTile; import com.android.systemui.quicksettings.WiFiDisplayTile; import com.android.systemui.quicksettings.WiFiTile; import com.android.systemui.quicksettings.WifiAPTile; import com.android.systemui.quicksettings.DesktopModeTile; import com.android.systemui.quicksettings.HybridTile; import com.android.systemui.quicksettings.RebootTile; import com.android.systemui.statusbar.powerwidget.PowerButton; import java.util.ArrayList; import java.util.HashMap; public class QuickSettingsController { private static String TAG = "QuickSettingsController"; // Stores the broadcast receivers and content observers // quick tiles register for. public HashMap<String, ArrayList<QuickSettingsTile>> mReceiverMap = new HashMap<String, ArrayList<QuickSettingsTile>>(); public HashMap<Uri, ArrayList<QuickSettingsTile>> mObserverMap = new HashMap<Uri, ArrayList<QuickSettingsTile>>(); private final Context mContext; private ArrayList<QuickSettingsTile> mQuickSettingsTiles; public PanelBar mBar; private final QuickSettingsContainerView mContainerView; private final Handler mHandler; private BroadcastReceiver mReceiver; private ContentObserver mObserver; public BaseStatusBar mStatusBarService; private InputMethodTile mIMETile; public QuickSettingsController(Context context, QuickSettingsContainerView container, BaseStatusBar statusBarService) { mContext = context; mContainerView = container; mHandler = new Handler(); mStatusBarService = statusBarService; mQuickSettingsTiles = new ArrayList<QuickSettingsTile>(); } void loadTiles() { // Reset reference tiles mIMETile = null; // Filter items not compatible with device boolean bluetoothSupported = deviceSupportsBluetooth(); boolean mobileDataSupported = deviceSupportsMobileData(mContext); if (!bluetoothSupported) { TILES_DEFAULT.remove(TILE_BLUETOOTH); } if (!mobileDataSupported) { TILES_DEFAULT.remove(TILE_WIFIAP); TILES_DEFAULT.remove(TILE_MOBILEDATA); TILES_DEFAULT.remove(TILE_NETWORKMODE); } // Read the stored list of tiles ContentResolver resolver = mContext.getContentResolver(); LayoutInflater inflater = LayoutInflater.from(mContext); String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS); if (tiles == null) { Log.i(TAG, "Default tiles being loaded"); tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT); } Log.i(TAG, "Tiles list: " + tiles); // Split out the tile names and add to the list for (String tile : tiles.split("\\|")) { QuickSettingsTile qs = null; if (tile.equals(TILE_USER)) { qs = new UserTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BATTERY)) { qs = new BatteryTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SETTINGS)) { qs = new PreferencesTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFI)) { qs = new WiFiTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_GPS)) { qs = new GPSTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) { qs = new BluetoothTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BRIGHTNESS)) { qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_RINGER)) { qs = new RingerModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SYNC)) { qs = new SyncTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFIAP) && mobileDataSupported) { qs = new WifiAPTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SCREENTIMEOUT)) { qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MOBILEDATA) && mobileDataSupported) { qs = new MobileNetworkTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_LOCKSCREEN)) { qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_AUTOROTATE)) { qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_AIRPLANE)) { qs = new AirplaneModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_TORCH)) { qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_SLEEP)) { qs = new SleepScreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_NFC)) { // User cannot add the NFC tile if the device does not support it // No need to check again here qs = new NfcTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_DESKTOPMODE)) { qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HYBRID)) { qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_VOLUME)) { qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_REBOOT)) { qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HOLOBAM)) { qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_NETWORKMODE) && mobileDataSupported) { qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BAMCONTROL)) { qs = new BamcontrolTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MUSIC)) { - qs = new MusicTile(mContext, inflater, mContainerView, this); + qs = new MusicTile(mContext, inflater, mContainerView, this, mHandler); } if (qs != null) { qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } } // Load the dynamic tiles // These toggles must be the last ones added to the view, as they will show // only when they are needed if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) { QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) { QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) { QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this); mIMETile.setupQuickSettingsTile(); mQuickSettingsTiles.add(mIMETile); if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) { QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } } public void setupQuickSettings() { mQuickSettingsTiles.clear(); mContainerView.removeAllViews(); // Clear out old receiver if (mReceiver != null) { mContext.unregisterReceiver(mReceiver); } mReceiver = new QSBroadcastReceiver(); mReceiverMap.clear(); ContentResolver resolver = mContext.getContentResolver(); // Clear out old observer if (mObserver != null) { resolver.unregisterContentObserver(mObserver); } mObserver = new QuickSettingsObserver(mHandler); mObserverMap.clear(); loadTiles(); setupBroadcastReceiver(); setupContentObserver(); } void setupContentObserver() { ContentResolver resolver = mContext.getContentResolver(); for (Uri uri : mObserverMap.keySet()) { resolver.registerContentObserver(uri, false, mObserver); } } private class QuickSettingsObserver extends ContentObserver { public QuickSettingsObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange, Uri uri) { ContentResolver resolver = mContext.getContentResolver(); for (QuickSettingsTile tile : mObserverMap.get(uri)) { tile.onChangeUri(resolver, uri); } } } void setupBroadcastReceiver() { IntentFilter filter = new IntentFilter(); for (String action : mReceiverMap.keySet()) { filter.addAction(action); } mContext.registerReceiver(mReceiver, filter); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void registerInMap(Object item, QuickSettingsTile tile, HashMap map) { if (map.keySet().contains(item)) { ArrayList list = (ArrayList) map.get(item); if (!list.contains(tile)) { list.add(tile); } } else { ArrayList<QuickSettingsTile> list = new ArrayList<QuickSettingsTile>(); list.add(tile); map.put(item, list); } } public void registerAction(Object action, QuickSettingsTile tile) { registerInMap(action, tile, mReceiverMap); } public void registerObservedContent(Uri uri, QuickSettingsTile tile) { registerInMap(uri, tile, mObserverMap); } private class QSBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action != null) { for (QuickSettingsTile t : mReceiverMap.get(action)) { t.onReceive(context, intent); } } } }; public void setBar(PanelBar bar) { mBar = bar; } public void setService(BaseStatusBar phoneStatusBar) { mStatusBarService = phoneStatusBar; } public void setImeWindowStatus(boolean visible) { if (mIMETile != null) { mIMETile.toggleVisibility(visible); } } public void updateResources() { mContainerView.updateResources(); for (QuickSettingsTile t : mQuickSettingsTiles) { t.updateResources(); } } }
true
true
void loadTiles() { // Reset reference tiles mIMETile = null; // Filter items not compatible with device boolean bluetoothSupported = deviceSupportsBluetooth(); boolean mobileDataSupported = deviceSupportsMobileData(mContext); if (!bluetoothSupported) { TILES_DEFAULT.remove(TILE_BLUETOOTH); } if (!mobileDataSupported) { TILES_DEFAULT.remove(TILE_WIFIAP); TILES_DEFAULT.remove(TILE_MOBILEDATA); TILES_DEFAULT.remove(TILE_NETWORKMODE); } // Read the stored list of tiles ContentResolver resolver = mContext.getContentResolver(); LayoutInflater inflater = LayoutInflater.from(mContext); String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS); if (tiles == null) { Log.i(TAG, "Default tiles being loaded"); tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT); } Log.i(TAG, "Tiles list: " + tiles); // Split out the tile names and add to the list for (String tile : tiles.split("\\|")) { QuickSettingsTile qs = null; if (tile.equals(TILE_USER)) { qs = new UserTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BATTERY)) { qs = new BatteryTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SETTINGS)) { qs = new PreferencesTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFI)) { qs = new WiFiTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_GPS)) { qs = new GPSTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) { qs = new BluetoothTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BRIGHTNESS)) { qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_RINGER)) { qs = new RingerModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SYNC)) { qs = new SyncTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFIAP) && mobileDataSupported) { qs = new WifiAPTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SCREENTIMEOUT)) { qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MOBILEDATA) && mobileDataSupported) { qs = new MobileNetworkTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_LOCKSCREEN)) { qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_AUTOROTATE)) { qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_AIRPLANE)) { qs = new AirplaneModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_TORCH)) { qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_SLEEP)) { qs = new SleepScreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_NFC)) { // User cannot add the NFC tile if the device does not support it // No need to check again here qs = new NfcTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_DESKTOPMODE)) { qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HYBRID)) { qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_VOLUME)) { qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_REBOOT)) { qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HOLOBAM)) { qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_NETWORKMODE) && mobileDataSupported) { qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BAMCONTROL)) { qs = new BamcontrolTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MUSIC)) { qs = new MusicTile(mContext, inflater, mContainerView, this); } if (qs != null) { qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } } // Load the dynamic tiles // These toggles must be the last ones added to the view, as they will show // only when they are needed if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) { QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) { QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) { QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this); mIMETile.setupQuickSettingsTile(); mQuickSettingsTiles.add(mIMETile); if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) { QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } }
void loadTiles() { // Reset reference tiles mIMETile = null; // Filter items not compatible with device boolean bluetoothSupported = deviceSupportsBluetooth(); boolean mobileDataSupported = deviceSupportsMobileData(mContext); if (!bluetoothSupported) { TILES_DEFAULT.remove(TILE_BLUETOOTH); } if (!mobileDataSupported) { TILES_DEFAULT.remove(TILE_WIFIAP); TILES_DEFAULT.remove(TILE_MOBILEDATA); TILES_DEFAULT.remove(TILE_NETWORKMODE); } // Read the stored list of tiles ContentResolver resolver = mContext.getContentResolver(); LayoutInflater inflater = LayoutInflater.from(mContext); String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS); if (tiles == null) { Log.i(TAG, "Default tiles being loaded"); tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT); } Log.i(TAG, "Tiles list: " + tiles); // Split out the tile names and add to the list for (String tile : tiles.split("\\|")) { QuickSettingsTile qs = null; if (tile.equals(TILE_USER)) { qs = new UserTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BATTERY)) { qs = new BatteryTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SETTINGS)) { qs = new PreferencesTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFI)) { qs = new WiFiTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_GPS)) { qs = new GPSTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) { qs = new BluetoothTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BRIGHTNESS)) { qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_RINGER)) { qs = new RingerModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SYNC)) { qs = new SyncTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_WIFIAP) && mobileDataSupported) { qs = new WifiAPTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_SCREENTIMEOUT)) { qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MOBILEDATA) && mobileDataSupported) { qs = new MobileNetworkTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_LOCKSCREEN)) { qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_AUTOROTATE)) { qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_AIRPLANE)) { qs = new AirplaneModeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_TORCH)) { qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_SLEEP)) { qs = new SleepScreenTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_NFC)) { // User cannot add the NFC tile if the device does not support it // No need to check again here qs = new NfcTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_DESKTOPMODE)) { qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HYBRID)) { qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_VOLUME)) { qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_REBOOT)) { qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_HOLOBAM)) { qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler); } else if (tile.equals(TILE_NETWORKMODE) && mobileDataSupported) { qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_BAMCONTROL)) { qs = new BamcontrolTile(mContext, inflater, mContainerView, this); } else if (tile.equals(TILE_MUSIC)) { qs = new MusicTile(mContext, inflater, mContainerView, this, mHandler); } if (qs != null) { qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } } // Load the dynamic tiles // These toggles must be the last ones added to the view, as they will show // only when they are needed if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) { QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) { QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) { QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this); mIMETile.setupQuickSettingsTile(); mQuickSettingsTiles.add(mIMETile); if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) { QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this); qs.setupQuickSettingsTile(); mQuickSettingsTiles.add(qs); } }
diff --git a/src/org/dyndns/pawitp/muwifiautologin/NetworkStateChanged.java b/src/org/dyndns/pawitp/muwifiautologin/NetworkStateChanged.java index e37d2aa..23254f1 100644 --- a/src/org/dyndns/pawitp/muwifiautologin/NetworkStateChanged.java +++ b/src/org/dyndns/pawitp/muwifiautologin/NetworkStateChanged.java @@ -1,45 +1,48 @@ package org.dyndns.pawitp.muwifiautologin; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.util.Log; public class NetworkStateChanged extends BroadcastReceiver { static final String TAG = "NetworkStateChanged"; static final String SSID = "MU-WiFi"; @Override public void onReceive(Context context, Intent intent) { // Check preference SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.getBoolean(Preferences.KEY_ENABLED, false)) { // Disable the BroadcastReceiver so it isn't called in the future Utils.setEnableBroadcastReceiver(context, false); return; } // Check network connected NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (!netInfo.isConnected()) { return; } // Check SSID WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); - if (!wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) { + if (wifi == null || !wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) { + // wifi is sometimes null on strange circumstances + // I've experienced it once connecting to a secured network with an invalid password + // others have reported this bug through the market return; } Log.v(TAG, "Connected to the correct network"); Intent i = new Intent(context, MuWifiLogin.class); context.startService(i); } }
true
true
public void onReceive(Context context, Intent intent) { // Check preference SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.getBoolean(Preferences.KEY_ENABLED, false)) { // Disable the BroadcastReceiver so it isn't called in the future Utils.setEnableBroadcastReceiver(context, false); return; } // Check network connected NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (!netInfo.isConnected()) { return; } // Check SSID WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) { return; } Log.v(TAG, "Connected to the correct network"); Intent i = new Intent(context, MuWifiLogin.class); context.startService(i); }
public void onReceive(Context context, Intent intent) { // Check preference SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.getBoolean(Preferences.KEY_ENABLED, false)) { // Disable the BroadcastReceiver so it isn't called in the future Utils.setEnableBroadcastReceiver(context, false); return; } // Check network connected NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (!netInfo.isConnected()) { return; } // Check SSID WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi == null || !wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) { // wifi is sometimes null on strange circumstances // I've experienced it once connecting to a secured network with an invalid password // others have reported this bug through the market return; } Log.v(TAG, "Connected to the correct network"); Intent i = new Intent(context, MuWifiLogin.class); context.startService(i); }
diff --git a/src/main/java/com/goodow/realtime/server/servlet/util/LocalDevServerFilter.java b/src/main/java/com/goodow/realtime/server/servlet/util/LocalDevServerFilter.java index 9a42ec0..5f7c433 100644 --- a/src/main/java/com/goodow/realtime/server/servlet/util/LocalDevServerFilter.java +++ b/src/main/java/com/goodow/realtime/server/servlet/util/LocalDevServerFilter.java @@ -1,62 +1,63 @@ /* * Copyright 2012 Goodow.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.goodow.realtime.server.servlet.util; import com.goodow.realtime.server.rpc.RpcUtil; import com.google.inject.Singleton; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; @Singleton public class LocalDevServerFilter implements Filter { private static final String APPLICATION_JSON = "application/json"; @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; - if (request.getMethod() == "POST" - && !request.getContentType().toLowerCase().startsWith(APPLICATION_JSON)) { + String contentType = request.getContentType(); + if (request.getMethod() == "POST" && contentType != null + && !contentType.toLowerCase().startsWith(APPLICATION_JSON)) { req = new HttpServletRequestWrapper(request) { @Override public String getContentType() { return APPLICATION_JSON; } }; } filterChain.doFilter(req, resp); ((HttpServletResponse) resp).setHeader(RpcUtil.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); } @Override public void init(FilterConfig arg0) throws ServletException { } }
true
true
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; if (request.getMethod() == "POST" && !request.getContentType().toLowerCase().startsWith(APPLICATION_JSON)) { req = new HttpServletRequestWrapper(request) { @Override public String getContentType() { return APPLICATION_JSON; } }; } filterChain.doFilter(req, resp); ((HttpServletResponse) resp).setHeader(RpcUtil.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); }
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String contentType = request.getContentType(); if (request.getMethod() == "POST" && contentType != null && !contentType.toLowerCase().startsWith(APPLICATION_JSON)) { req = new HttpServletRequestWrapper(request) { @Override public String getContentType() { return APPLICATION_JSON; } }; } filterChain.doFilter(req, resp); ((HttpServletResponse) resp).setHeader(RpcUtil.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); }
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java index d969033..f0cb198 100644 --- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java +++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java @@ -1,136 +1,136 @@ /** * N3X15's Handy Dandy Mountain Generator * From MineEdit * * INSERT BSD HERE */ package net.nexisonline.spade.chunkproviders; import java.util.Random; import java.util.logging.Logger; import libnoiseforjava.NoiseGen.NoiseQuality; import libnoiseforjava.module.Perlin; import libnoiseforjava.module.RidgedMulti; import net.nexisonline.spade.Interpolator; import org.bukkit.ChunkProvider; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; /** * @author Rob * */ public class ChunkProviderMountains extends ChunkProvider { private RidgedMulti terrainNoise; private Perlin continentNoise; private int continentNoiseOctaves = 16; private NoiseQuality noiseQuality = NoiseQuality.QUALITY_STD; private double ContinentNoiseFrequency; /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#onLoad(org.bukkit.World, long) */ @Override public void onLoad(World world, long seed) { this.setHasCustomTerrain(true); double Frequency = 0.1; double Lacunarity = 0.05; double Persistance = 0.25; int OctaveCount = continentNoiseOctaves = 4; try { terrainNoise = new RidgedMulti(); continentNoise = new Perlin(); terrainNoise.setSeed((int) seed); continentNoise.setSeed((int) seed + 2); terrainNoise.setFrequency(Frequency); terrainNoise.setNoiseQuality(noiseQuality); terrainNoise.setOctaveCount(OctaveCount); terrainNoise.setLacunarity(Lacunarity); //continentNoise.setFrequency(ContinentNoiseFrequency); //continentNoise.setNoiseQuality(noiseQuality); continentNoise.setOctaveCount(continentNoiseOctaves); //continentNoise.setLacunarity(Lacunarity); //continentNoise.setPersistence(Persistance); } catch (Exception e) { } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[], * org.bukkit.block.Biome[], double[]) */ @Override public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = Integer.MAX_VALUE; for (int x = 0; x < 16; x+=3) { for (int z = 0; z < 16; z+=3) { // Generate our continental noise. double dheight = continentNoise.getValue( (double) (x + (X * 16)) * 0.01, (double) (z + (Z * 16)) * 0.01, 0);// *5d; // 2.0 /* // Add a wee bit o' terrain noise on top. height += ((terrainNoise.getValue( (x + (X * 16)/1), (z + (Z * 16)/1), 0) )/10d); */ int height = (int)((dheight*32d)+96d); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y+=3) { abyte[getBlockIndex(x,y,z)]=(y <= height) ? (byte) 1 : (byte) 0; // Fill; } } } Interpolator.LinearExpand(abyte); - for (int x = 0; x < 16; x+=3) { - for (int z = 0; z < 16; z+=3) { - for (int y = 0; y < 128; y+=3) { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < 128; y++) { byte block = abyte[getBlockIndex(x,y,z)]; block = (block>0) ? (byte)1 : (byte)0; // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); // Old cave stuff, handled by CraftBukkit now. // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Mountains] Chunk (%d,%d) Min Height: %dm",X,Z,minHeight)); } }
true
true
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = Integer.MAX_VALUE; for (int x = 0; x < 16; x+=3) { for (int z = 0; z < 16; z+=3) { // Generate our continental noise. double dheight = continentNoise.getValue( (double) (x + (X * 16)) * 0.01, (double) (z + (Z * 16)) * 0.01, 0);// *5d; // 2.0 /* // Add a wee bit o' terrain noise on top. height += ((terrainNoise.getValue( (x + (X * 16)/1), (z + (Z * 16)/1), 0) )/10d); */ int height = (int)((dheight*32d)+96d); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y+=3) { abyte[getBlockIndex(x,y,z)]=(y <= height) ? (byte) 1 : (byte) 0; // Fill; } } } Interpolator.LinearExpand(abyte); for (int x = 0; x < 16; x+=3) { for (int z = 0; z < 16; z+=3) { for (int y = 0; y < 128; y+=3) { byte block = abyte[getBlockIndex(x,y,z)]; block = (block>0) ? (byte)1 : (byte)0; // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); // Old cave stuff, handled by CraftBukkit now. // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Mountains] Chunk (%d,%d) Min Height: %dm",X,Z,minHeight)); }
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = Integer.MAX_VALUE; for (int x = 0; x < 16; x+=3) { for (int z = 0; z < 16; z+=3) { // Generate our continental noise. double dheight = continentNoise.getValue( (double) (x + (X * 16)) * 0.01, (double) (z + (Z * 16)) * 0.01, 0);// *5d; // 2.0 /* // Add a wee bit o' terrain noise on top. height += ((terrainNoise.getValue( (x + (X * 16)/1), (z + (Z * 16)/1), 0) )/10d); */ int height = (int)((dheight*32d)+96d); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y+=3) { abyte[getBlockIndex(x,y,z)]=(y <= height) ? (byte) 1 : (byte) 0; // Fill; } } } Interpolator.LinearExpand(abyte); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 128; y++) { byte block = abyte[getBlockIndex(x,y,z)]; block = (block>0) ? (byte)1 : (byte)0; // If below height, set rock. Otherwise, set air. block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // Origin point + sand to prevent 5000 years of loading. if(x==0&&z==0&&X==x&&Z==z&&y<=63) block=(byte) ((y==63)?12:7); // Old cave stuff, handled by CraftBukkit now. // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } Logger.getLogger("Minecraft").info(String.format("[Mountains] Chunk (%d,%d) Min Height: %dm",X,Z,minHeight)); }
diff --git a/src/main/java/pl/bitethebet/repository/UserAccountRepository.java b/src/main/java/pl/bitethebet/repository/UserAccountRepository.java index 7631d6d..61f7ccf 100644 --- a/src/main/java/pl/bitethebet/repository/UserAccountRepository.java +++ b/src/main/java/pl/bitethebet/repository/UserAccountRepository.java @@ -1,24 +1,23 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pl.bitethebet.repository; import java.util.List; import org.springframework.stereotype.Repository; import pl.bitethebet.model.UserAccount; import pl.bitethebet.repository.common.CrudRepository; /** * * @author mrowkam */ @Repository public class UserAccountRepository extends CrudRepository<UserAccount> { public UserAccount findByUsername(String username) { List<UserAccount> us = (List<UserAccount>) findBySingleParamQuery(UserAccount.class, "username == " + username); - System.out.println(us.get(0).getUsername()); return us.get(0); } }
true
true
public UserAccount findByUsername(String username) { List<UserAccount> us = (List<UserAccount>) findBySingleParamQuery(UserAccount.class, "username == " + username); System.out.println(us.get(0).getUsername()); return us.get(0); }
public UserAccount findByUsername(String username) { List<UserAccount> us = (List<UserAccount>) findBySingleParamQuery(UserAccount.class, "username == " + username); return us.get(0); }
diff --git a/common/logisticspipes/logic/LogicSupplier.java b/common/logisticspipes/logic/LogicSupplier.java index 75c5e458..15934941 100644 --- a/common/logisticspipes/logic/LogicSupplier.java +++ b/common/logisticspipes/logic/LogicSupplier.java @@ -1,242 +1,242 @@ /** * Copyright (c) Krapht, 2011 * * "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license located in * http://www.mod-buildcraft.com/MMPL-1.0.txt */ package logisticspipes.logic; import java.util.HashMap; import java.util.Map.Entry; import logisticspipes.LogisticsPipes; import logisticspipes.interfaces.IChassiePowerProvider; import logisticspipes.interfaces.IInventoryUtil; import logisticspipes.interfaces.routing.IRequestItems; import logisticspipes.interfaces.routing.IRequireReliableTransport; import logisticspipes.network.GuiIDs; import logisticspipes.network.NetworkConstants; import logisticspipes.network.packets.PacketPipeInteger; import logisticspipes.pipefxhandlers.Particles; import logisticspipes.pipes.PipeItemsSupplierLogistics; import logisticspipes.pipes.basic.CoreRoutedPipe; import logisticspipes.proxy.MainProxy; import logisticspipes.proxy.SimpleServiceLocator; import logisticspipes.request.RequestManager; import logisticspipes.utils.AdjacentTile; import logisticspipes.utils.ItemIdentifier; import logisticspipes.utils.ItemIdentifierStack; import logisticspipes.utils.SimpleInventory; import logisticspipes.utils.WorldUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.nbt.NBTTagCompound; import buildcraft.energy.EngineWood; import buildcraft.energy.TileEngine; import buildcraft.transport.TileGenericPipe; import cpw.mods.fml.common.network.Player; public class LogicSupplier extends BaseRoutingLogic implements IRequireReliableTransport{ private SimpleInventory dummyInventory = new SimpleInventory(9, "Items to keep stocked", 127); private final HashMap<ItemIdentifier, Integer> _requestedItems = new HashMap<ItemIdentifier, Integer>(); private boolean _requestPartials = false; private int _lastSucess_count = 1024; public boolean pause = false; public IChassiePowerProvider _power; public LogicSupplier() { throttleTime = 100; } @Override public void destroy() {} @Override public void onWrenchClicked(EntityPlayer entityplayer) { //pause = true; //Pause until GUI is closed //TODO Find a way to handle this if(MainProxy.isServer(entityplayer.worldObj)) { //GuiProxy.openGuiSupplierPipe(entityplayer.inventory, dummyInventory, this); entityplayer.openGui(LogisticsPipes.instance, GuiIDs.GUI_SupplierPipe_ID, worldObj, xCoord, yCoord, zCoord); MainProxy.sendPacketToPlayer(new PacketPipeInteger(NetworkConstants.SUPPLIER_PIPE_MODE_RESPONSE, xCoord, yCoord, zCoord, isRequestingPartials() ? 1 : 0).getPacket(), (Player)entityplayer); } } /*** GUI ***/ public SimpleInventory getDummyInventory() { return dummyInventory; } @Override public void throttledUpdateEntity() { if (!((CoreRoutedPipe)this.container.pipe).isEnabled()){ return; } if(MainProxy.isClient(this.worldObj)) return; if (pause) return; super.throttledUpdateEntity(); for(int amount : _requestedItems.values()) { if(amount > 0) { MainProxy.sendSpawnParticlePacket(Particles.VioletParticle, xCoord, yCoord, zCoord, this.worldObj, 2); } } WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord); for (AdjacentTile tile : worldUtil.getAdjacentTileEntities(true)){ if (tile.tile instanceof TileGenericPipe) continue; if (!(tile.tile instanceof IInventory)) continue; //Do not attempt to supply redstone engines if (tile.tile instanceof TileEngine && ((TileEngine)tile.tile).engine instanceof EngineWood) continue; IInventory inv = (IInventory) tile.tile; if (inv.getSizeInventory() < 1) continue; IInventoryUtil invUtil = SimpleServiceLocator.inventoryUtilFactory.getInventoryUtil(inv); //How many do I want? HashMap<ItemIdentifier, Integer> needed = new HashMap<ItemIdentifier, Integer>(dummyInventory.getItemsAndCount()); //How many do I have? HashMap<ItemIdentifier, Integer> have = invUtil.getItemsAndCount(); //Reduce what I have for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ - Integer haveCount = have.get(item); + Integer haveCount = have.get(item.getKey()); if (haveCount != null){ item.setValue(item.getValue() - haveCount); } } //Reduce what have been requested already for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ - Integer requestedCount = _requestedItems.get(item); + Integer requestedCount = _requestedItems.get(item.getKey()); if (requestedCount!=null){ item.setValue(item.getValue() - requestedCount); } } ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(false); //List<SearchNode> valid = getRouter().getIRoutersByCost(); /* //TODO Double Chests, Simplyfication // Filter out providers attached to this inventory so that we don't get stuck in an // endless supply/provide loop on this inventory. WorldUtil invWU = new WorldUtil(tile.tile.worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord); ArrayList<IProvideItems> invProviders = new ArrayList<IProvideItems>(); for (AdjacentTile atile : invWU.getAdjacentTileEntities()) { if ((atile.tile instanceof TileGenericPipe)) { Pipe p = ((TileGenericPipe) atile.tile).pipe; if ((p instanceof IProvideItems)) { invProviders.add((IProvideItems) p); } } } for (IRouter r : valid) { CoreRoutedPipe cp = r.getPipe(); if (((cp instanceof IProvideItems)) && (invProviders.contains((IProvideItems) cp))) { valid.remove(r); } } */ //Make request for (Entry<ItemIdentifier, Integer> need : needed.entrySet()){ Integer amountRequested = need.getValue(); if (amountRequested==null || amountRequested < 1) continue; int neededCount; if(_requestPartials) neededCount = Math.min(amountRequested,this._lastSucess_count); else neededCount=amountRequested; if(!_power.useEnergy(10)) { break; } boolean success = false; do{ success = RequestManager.request(need.getKey().makeStack(neededCount), (IRequestItems) container.pipe, null); if (success || neededCount == 1){ break; } neededCount = neededCount / 2; } while (_requestPartials && !success); if (success){ if(neededCount == amountRequested) _lastSucess_count=1024; else { if(neededCount == _lastSucess_count) _lastSucess_count *= 2; else _lastSucess_count= neededCount; } - Integer currentRequest = _requestedItems.get(need); + Integer currentRequest = _requestedItems.get(need.getKey()); if (currentRequest == null){ _requestedItems.put(need.getKey(), neededCount); }else { _requestedItems.put(need.getKey(), currentRequest + neededCount); } } else{ _lastSucess_count=1; ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(true); } } } } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); dummyInventory.readFromNBT(nbttagcompound, ""); _requestPartials = nbttagcompound.getBoolean("requestpartials"); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); dummyInventory.writeToNBT(nbttagcompound, ""); nbttagcompound.setBoolean("requestpartials", _requestPartials); } @Override public void itemLost(ItemIdentifierStack item) { Integer count = _requestedItems.get(item.getItem()); if (count != null){ _requestedItems.put(item.getItem(), Math.max(0, count - item.stackSize)); } } @Override public void itemArrived(ItemIdentifierStack item) { Integer count = _requestedItems.get(item.getItem()); if (count != null){ _requestedItems.put(item.getItem(), Math.max(0, count - item.stackSize)); } } public boolean isRequestingPartials(){ return _requestPartials; } public void setRequestingPartials(boolean value){ _requestPartials = value; } }
false
true
public void throttledUpdateEntity() { if (!((CoreRoutedPipe)this.container.pipe).isEnabled()){ return; } if(MainProxy.isClient(this.worldObj)) return; if (pause) return; super.throttledUpdateEntity(); for(int amount : _requestedItems.values()) { if(amount > 0) { MainProxy.sendSpawnParticlePacket(Particles.VioletParticle, xCoord, yCoord, zCoord, this.worldObj, 2); } } WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord); for (AdjacentTile tile : worldUtil.getAdjacentTileEntities(true)){ if (tile.tile instanceof TileGenericPipe) continue; if (!(tile.tile instanceof IInventory)) continue; //Do not attempt to supply redstone engines if (tile.tile instanceof TileEngine && ((TileEngine)tile.tile).engine instanceof EngineWood) continue; IInventory inv = (IInventory) tile.tile; if (inv.getSizeInventory() < 1) continue; IInventoryUtil invUtil = SimpleServiceLocator.inventoryUtilFactory.getInventoryUtil(inv); //How many do I want? HashMap<ItemIdentifier, Integer> needed = new HashMap<ItemIdentifier, Integer>(dummyInventory.getItemsAndCount()); //How many do I have? HashMap<ItemIdentifier, Integer> have = invUtil.getItemsAndCount(); //Reduce what I have for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ Integer haveCount = have.get(item); if (haveCount != null){ item.setValue(item.getValue() - haveCount); } } //Reduce what have been requested already for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ Integer requestedCount = _requestedItems.get(item); if (requestedCount!=null){ item.setValue(item.getValue() - requestedCount); } } ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(false); //List<SearchNode> valid = getRouter().getIRoutersByCost(); /* //TODO Double Chests, Simplyfication // Filter out providers attached to this inventory so that we don't get stuck in an // endless supply/provide loop on this inventory. WorldUtil invWU = new WorldUtil(tile.tile.worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord); ArrayList<IProvideItems> invProviders = new ArrayList<IProvideItems>(); for (AdjacentTile atile : invWU.getAdjacentTileEntities()) { if ((atile.tile instanceof TileGenericPipe)) { Pipe p = ((TileGenericPipe) atile.tile).pipe; if ((p instanceof IProvideItems)) { invProviders.add((IProvideItems) p); } } } for (IRouter r : valid) { CoreRoutedPipe cp = r.getPipe(); if (((cp instanceof IProvideItems)) && (invProviders.contains((IProvideItems) cp))) { valid.remove(r); } } */ //Make request for (Entry<ItemIdentifier, Integer> need : needed.entrySet()){ Integer amountRequested = need.getValue(); if (amountRequested==null || amountRequested < 1) continue; int neededCount; if(_requestPartials) neededCount = Math.min(amountRequested,this._lastSucess_count); else neededCount=amountRequested; if(!_power.useEnergy(10)) { break; } boolean success = false; do{ success = RequestManager.request(need.getKey().makeStack(neededCount), (IRequestItems) container.pipe, null); if (success || neededCount == 1){ break; } neededCount = neededCount / 2; } while (_requestPartials && !success); if (success){ if(neededCount == amountRequested) _lastSucess_count=1024; else { if(neededCount == _lastSucess_count) _lastSucess_count *= 2; else _lastSucess_count= neededCount; } Integer currentRequest = _requestedItems.get(need); if (currentRequest == null){ _requestedItems.put(need.getKey(), neededCount); }else { _requestedItems.put(need.getKey(), currentRequest + neededCount); } } else{ _lastSucess_count=1; ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(true); } } } }
public void throttledUpdateEntity() { if (!((CoreRoutedPipe)this.container.pipe).isEnabled()){ return; } if(MainProxy.isClient(this.worldObj)) return; if (pause) return; super.throttledUpdateEntity(); for(int amount : _requestedItems.values()) { if(amount > 0) { MainProxy.sendSpawnParticlePacket(Particles.VioletParticle, xCoord, yCoord, zCoord, this.worldObj, 2); } } WorldUtil worldUtil = new WorldUtil(worldObj, xCoord, yCoord, zCoord); for (AdjacentTile tile : worldUtil.getAdjacentTileEntities(true)){ if (tile.tile instanceof TileGenericPipe) continue; if (!(tile.tile instanceof IInventory)) continue; //Do not attempt to supply redstone engines if (tile.tile instanceof TileEngine && ((TileEngine)tile.tile).engine instanceof EngineWood) continue; IInventory inv = (IInventory) tile.tile; if (inv.getSizeInventory() < 1) continue; IInventoryUtil invUtil = SimpleServiceLocator.inventoryUtilFactory.getInventoryUtil(inv); //How many do I want? HashMap<ItemIdentifier, Integer> needed = new HashMap<ItemIdentifier, Integer>(dummyInventory.getItemsAndCount()); //How many do I have? HashMap<ItemIdentifier, Integer> have = invUtil.getItemsAndCount(); //Reduce what I have for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ Integer haveCount = have.get(item.getKey()); if (haveCount != null){ item.setValue(item.getValue() - haveCount); } } //Reduce what have been requested already for (Entry<ItemIdentifier, Integer> item : needed.entrySet()){ Integer requestedCount = _requestedItems.get(item.getKey()); if (requestedCount!=null){ item.setValue(item.getValue() - requestedCount); } } ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(false); //List<SearchNode> valid = getRouter().getIRoutersByCost(); /* //TODO Double Chests, Simplyfication // Filter out providers attached to this inventory so that we don't get stuck in an // endless supply/provide loop on this inventory. WorldUtil invWU = new WorldUtil(tile.tile.worldObj, tile.tile.xCoord, tile.tile.yCoord, tile.tile.zCoord); ArrayList<IProvideItems> invProviders = new ArrayList<IProvideItems>(); for (AdjacentTile atile : invWU.getAdjacentTileEntities()) { if ((atile.tile instanceof TileGenericPipe)) { Pipe p = ((TileGenericPipe) atile.tile).pipe; if ((p instanceof IProvideItems)) { invProviders.add((IProvideItems) p); } } } for (IRouter r : valid) { CoreRoutedPipe cp = r.getPipe(); if (((cp instanceof IProvideItems)) && (invProviders.contains((IProvideItems) cp))) { valid.remove(r); } } */ //Make request for (Entry<ItemIdentifier, Integer> need : needed.entrySet()){ Integer amountRequested = need.getValue(); if (amountRequested==null || amountRequested < 1) continue; int neededCount; if(_requestPartials) neededCount = Math.min(amountRequested,this._lastSucess_count); else neededCount=amountRequested; if(!_power.useEnergy(10)) { break; } boolean success = false; do{ success = RequestManager.request(need.getKey().makeStack(neededCount), (IRequestItems) container.pipe, null); if (success || neededCount == 1){ break; } neededCount = neededCount / 2; } while (_requestPartials && !success); if (success){ if(neededCount == amountRequested) _lastSucess_count=1024; else { if(neededCount == _lastSucess_count) _lastSucess_count *= 2; else _lastSucess_count= neededCount; } Integer currentRequest = _requestedItems.get(need.getKey()); if (currentRequest == null){ _requestedItems.put(need.getKey(), neededCount); }else { _requestedItems.put(need.getKey(), currentRequest + neededCount); } } else{ _lastSucess_count=1; ((PipeItemsSupplierLogistics)this.container.pipe).setRequestFailed(true); } } } }
diff --git a/src/com/rapplogic/xbee/api/HardwareVersion.java b/src/com/rapplogic/xbee/api/HardwareVersion.java index bcd947b..feedf4d 100644 --- a/src/com/rapplogic/xbee/api/HardwareVersion.java +++ b/src/com/rapplogic/xbee/api/HardwareVersion.java @@ -1,75 +1,75 @@ /** * Copyright (c) 2008 Andrew Rapp. All rights reserved. * * This file is part of XBee-API. * * XBee-API is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * XBee-API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBee-API. If not, see <http://www.gnu.org/licenses/>. */ package com.rapplogic.xbee.api; /** * Represents a XBee Address. * <p/> * @author andrew * */ public class HardwareVersion { public enum RadioType { SERIES1("Series 1"), SERIES1_PRO("Series 1 Pro"), SERIES2("Series 2"), SERIES2_PRO("Series 2 Pro"), SERIES2B_PRO("Series 2B Pro"), UNKNOWN("Unknown"); private String name; RadioType(String name) { this.name = name; } public String toString() { return name; } } public static RadioType parse(AtCommandResponse response) throws XBeeException { - if (response.getCommand().equals("HV")) { + if (!response.getCommand().equals("HV")) { throw new IllegalArgumentException("This is only applicable to the HV command"); } if (!response.isOk()) { throw new XBeeException("Attempt to query HV parameter failed"); } switch (response.getValue()[0]) { case 0x17: return RadioType.SERIES1; case 0x18: return RadioType.SERIES1_PRO; case 0x19: return RadioType.SERIES2; case 0x1a: return RadioType.SERIES2_PRO; case 0x1e: return RadioType.SERIES2B_PRO; } return RadioType.UNKNOWN; } }
true
true
public static RadioType parse(AtCommandResponse response) throws XBeeException { if (response.getCommand().equals("HV")) { throw new IllegalArgumentException("This is only applicable to the HV command"); } if (!response.isOk()) { throw new XBeeException("Attempt to query HV parameter failed"); } switch (response.getValue()[0]) { case 0x17: return RadioType.SERIES1; case 0x18: return RadioType.SERIES1_PRO; case 0x19: return RadioType.SERIES2; case 0x1a: return RadioType.SERIES2_PRO; case 0x1e: return RadioType.SERIES2B_PRO; } return RadioType.UNKNOWN; }
public static RadioType parse(AtCommandResponse response) throws XBeeException { if (!response.getCommand().equals("HV")) { throw new IllegalArgumentException("This is only applicable to the HV command"); } if (!response.isOk()) { throw new XBeeException("Attempt to query HV parameter failed"); } switch (response.getValue()[0]) { case 0x17: return RadioType.SERIES1; case 0x18: return RadioType.SERIES1_PRO; case 0x19: return RadioType.SERIES2; case 0x1a: return RadioType.SERIES2_PRO; case 0x1e: return RadioType.SERIES2B_PRO; } return RadioType.UNKNOWN; }
diff --git a/baixing_quanleimu/src/com/quanleimu/view/fragment/SetMainFragment.java b/baixing_quanleimu/src/com/quanleimu/view/fragment/SetMainFragment.java index 073a009c..db877210 100644 --- a/baixing_quanleimu/src/com/quanleimu/view/fragment/SetMainFragment.java +++ b/baixing_quanleimu/src/com/quanleimu/view/fragment/SetMainFragment.java @@ -1,394 +1,394 @@ package com.quanleimu.view.fragment; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.quanleimu.activity.BaseFragment; import com.quanleimu.activity.QuanleimuApplication; import com.quanleimu.activity.QuanleimuMainActivity; import com.quanleimu.activity.R; import com.quanleimu.entity.UserBean; import com.quanleimu.util.BXUpdateService; import com.quanleimu.util.Communication; import com.quanleimu.util.ParameterHolder; import com.quanleimu.util.Util; import org.json.JSONException; import org.json.JSONObject; //import com.quanleimu.entity.AuthDialogListener; //import com.quanleimu.entity.WeiboAccessTokenWrapper; //import com.weibo.net.AccessToken; //import com.weibo.net.Oauth2AccessTokenHeader; //import com.weibo.net.Utility; //import com.weibo.net.Weibo; //import com.weibo.net.WeiboParameters; public class SetMainFragment extends BaseFragment implements View.OnClickListener { private final int MSG_NETWORK_ERROR = 0; private final int MSG_DOWNLOAD_APP = 1; private final int MSG_INSTALL_APP = 3; private final int MSG_HAS_NEW_VERSION = 4; private ProgressDialog pd; private String serverVersion = ""; // 定义控件 public Dialog changePhoneDialog; private UserBean user; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View setmain = inflater.inflate(R.layout.setmain, null); ((RelativeLayout) setmain.findViewById(R.id.setFlowOptimize)).setOnClickListener(this); ((RelativeLayout) setmain.findViewById(R.id.setBindID)).setOnClickListener(this); ((RelativeLayout) setmain.findViewById(R.id.setCheckUpdate)).setOnClickListener(this); ((RelativeLayout) setmain.findViewById(R.id.setAbout)).setOnClickListener(this); ((RelativeLayout) setmain.findViewById(R.id.setFeedback)).setOnClickListener(this); // WeiboAccessTokenWrapper tokenWrapper = (WeiboAccessTokenWrapper)Helper.loadDataFromLocate(this.getActivity(), "weiboToken"); // AccessToken token = null; // if(tokenWrapper != null && tokenWrapper.getToken() != null){ // token = new AccessToken(tokenWrapper.getToken(), QuanleimuApplication.kWBBaixingAppSecret); // token.setExpiresIn(tokenWrapper.getExpires()); // } // String nick = (String)Helper.loadDataFromLocate(this.getActivity(), "weiboNickName"); // if(token != null && nick != null){ // ((TextView)setmain.findViewById(R.id.tvWeiboNick)).setText(nick); // if(QuanleimuApplication.getWeiboAccessToken() == null){ // QuanleimuApplication.setWeiboAccessToken(token); // } // } // final TextView textImg = (TextView)setmain.findViewById(R.id.textView3); // if(QuanleimuApplication.isTextMode()){ // textImg.setText("文字"); // } // else{ // textImg.setText("图片"); // } // ((RelativeLayout)setmain.findViewById(R.id.rlTextImage)).setOnClickListener(new View.OnClickListener() { // // @Override // public void onClick(View v) { // if(textImg.getText().equals("图片")){ // textImg.setText("文字"); // QuanleimuApplication.setTextMode(true); // } // else{ // textImg.setText("图片"); // QuanleimuApplication.setTextMode(false); // } // } // }); // ((TextView)setmain.findViewById(R.id.personMark)).setText(QuanleimuApplication.getApplication().getPersonMark()); refreshUI(setmain); return setmain; } private void refreshUI(View rootView) { user = Util.getCurrentUser(); TextView bindIdTextView = (TextView) rootView.findViewById(R.id.setBindIdtextView); if (user == null || user.getPhone() == null || user.getPhone().equals("")) { bindIdTextView.setText(R.string.label_login); } else { bindIdTextView.setText(R.string.label_logout); } } public void onResume() { super.onResume(); // ((TextView)getView().findViewById(R.id.personMark)).setText(QuanleimuApplication.getApplication().getPersonMark()); this.refreshUI(getView()); } @Override public void initTitle(TitleDef title) { title.m_visible = true; title.m_title = "设置"; title.m_leftActionHint = "完成"; title.m_leftActionStyle = EBUTT_STYLE.EBUTT_STYLE_NORMAL; } @Override public void initTab(TabDef tab) { tab.m_visible = false; } private void logoutAction() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_confirm_logout) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Util.logout(); Toast.makeText(getAppContext(), "已退出", 1).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }).create().show(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.setFlowOptimize: showFlowOptimizeDialog(); break; case R.id.setBindID: - if (user == null) { + if (user == null || user.getPhone() == null || user.getPhone().equals("")) { Bundle bundle = createArguments(null, "用户中心"); pushFragment(new LoginFragment(), bundle); } else { //TODO jiawu 加入确认退出过程 logoutAction(); refreshUI(getView()); } break; case R.id.setCheckUpdate: checkNewVersion(); break; case R.id.setAbout: pushFragment(new AboutUsFragment(), null); break; case R.id.setFeedback: pushFragment(new FeedbackFragment(), createArguments(null, null)); break; default: Toast.makeText(getAppContext(), "no action", 1).show(); break; } // 手机号码 // if(v.getId() == R.id.rlWeibo){ // if(QuanleimuApplication.getWeiboAccessToken() != null){ // AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // builder.setTitle("提示:") // .setMessage("是否解除绑定?") // .setNegativeButton("否", null) // .setPositiveButton("是", // new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, // int which) { // // Helper.saveDataToLocate(getActivity(), "weiboToken", null); // Helper.saveDataToLocate(getActivity(), "weiboNickName", null); // QuanleimuApplication.setWeiboAccessToken(null); // Weibo.getInstance().setAccessToken(null); // Weibo.getInstance().setRequestToken(null); // Weibo.getInstance().setupConsumerConfig("", ""); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(""); // } // }); // builder.create().show(); // } // else{ // Weibo weibo = Weibo.getInstance(); // weibo.setupConsumerConfig(QuanleimuApplication.kWBBaixingAppKey, QuanleimuApplication.kWBBaixingAppSecret); // weibo.setRedirectUrl("http://www.baixing.com"); //// weibo.authorize((BaseActivity)this.getContext(), new AuthDialogListener()); // WeiboParameters parameters=new WeiboParameters(); // parameters.add("forcelogin", "true"); // Utility.setAuthorization(new Oauth2AccessTokenHeader()); // AuthDialogListener lsn = new AuthDialogListener(getActivity(), new AuthDialogListener.AuthListener(){ // @Override // public void onComplete(){ // String nick = (String)Helper.loadDataFromLocate(getActivity(), "weiboNickName"); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(nick); // } // }); // weibo.dialog(getActivity(), // parameters, lsn); // lsn.setInAuthrize(true); // } // } /* final View root = getView(); // 签名档 if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlMark)).getId()) { pushFragment(new MarkLableFragment(), null ); } // 清空缓存 else if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlClearCache)).getId()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_title_info) .setMessage(R.string.dialog_message_confirm_clear_cache) .setNegativeButton(R.string.no, null) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String[] files = getActivity().fileList(); for(int i=0;i<files.length;i++){ String file_path = files[i]; getActivity().deleteFile(file_path); } QuanleimuApplication.getApplication().ClearCache(); //清空签名档 // ((TextView)root.findViewById(R.id.personMark)).setText(""); } }); builder.create().show(); } */ } @Override protected void handleMessage(Message msg, Activity activity, View rootView) { super.handleMessage(msg, activity, rootView); switch (msg.what) { case MSG_NETWORK_ERROR: Toast.makeText(getActivity(), msg.obj.toString(), 1).show(); break; case MSG_DOWNLOAD_APP: updateAppDownload(msg.obj.toString()); break; case MSG_INSTALL_APP: updateAppInstall(); break; case MSG_HAS_NEW_VERSION: final String apkUrl = msg.obj.toString(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("检查更新") .setMessage("当前版本: " + QuanleimuApplication.version + "\n发现新版本: " + serverVersion + "\n是否更新?") .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sendMessage(MSG_DOWNLOAD_APP, apkUrl); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }).create().show(); break; } if (pd != null) { pd.hide(); } } /** * 省流量设置 */ private void showFlowOptimizeDialog() { int checkedIdx = QuanleimuApplication.isTextMode() ? 1 : 0; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.label_flow_optimize) .setSingleChoiceItems(R.array.item_flow_optimize, checkedIdx, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { QuanleimuApplication.setTextMode(i == 1); dialog.dismiss(); String tip = (i == 1) ? "省流量模式" : "图片模式"; Toast.makeText(getActivity(), "已切换至" + tip, 1).show(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }).create().show(); } /** * 检查版本更新 */ private void checkNewVersion() { ParameterHolder params = new ParameterHolder(); params.addParameter("clientVersion", QuanleimuApplication.version); pd = ProgressDialog.show(SetMainFragment.this.getActivity(), "提示", "请稍候..."); pd.show(); Communication.executeAsyncGetTask("check_version", params, new Communication.CommandListener() { @Override public void onServerResponse(String serverMessage) { try { JSONObject respond = new JSONObject(serverMessage); JSONObject error = respond.getJSONObject("error"); final String apkUrl = respond.getString("apkUrl"); serverVersion = respond.getString("serverVersion"); if (!"0".equals(error.getString("code"))) { sendMessage(MSG_NETWORK_ERROR, error.getString("message")); } else { if (respond.getBoolean("hasNew")) { sendMessage(MSG_HAS_NEW_VERSION, apkUrl); } else { } } } catch (JSONException e) { sendMessage(MSG_NETWORK_ERROR, "网络异常"); } } @Override public void onException(Exception ex) { sendMessage(MSG_NETWORK_ERROR, "网络异常"); } }); } private void updateAppDownload(String apkUrl) { //开启更新服务UpdateService //这里为了把update更好模块化,可以传一些updateService依赖的值 //如布局ID,资源ID,动态获取的标题,这里以app_name为例 Intent updateIntent =new Intent(getAppContext(), BXUpdateService.class); updateIntent.putExtra("titleId",R.string.app_name); updateIntent.putExtra("apkUrl", apkUrl); getAppContext().startService(updateIntent); } private void updateAppInstall() { } }
true
true
public void onClick(View v) { switch (v.getId()) { case R.id.setFlowOptimize: showFlowOptimizeDialog(); break; case R.id.setBindID: if (user == null) { Bundle bundle = createArguments(null, "用户中心"); pushFragment(new LoginFragment(), bundle); } else { //TODO jiawu 加入确认退出过程 logoutAction(); refreshUI(getView()); } break; case R.id.setCheckUpdate: checkNewVersion(); break; case R.id.setAbout: pushFragment(new AboutUsFragment(), null); break; case R.id.setFeedback: pushFragment(new FeedbackFragment(), createArguments(null, null)); break; default: Toast.makeText(getAppContext(), "no action", 1).show(); break; } // 手机号码 // if(v.getId() == R.id.rlWeibo){ // if(QuanleimuApplication.getWeiboAccessToken() != null){ // AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // builder.setTitle("提示:") // .setMessage("是否解除绑定?") // .setNegativeButton("否", null) // .setPositiveButton("是", // new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, // int which) { // // Helper.saveDataToLocate(getActivity(), "weiboToken", null); // Helper.saveDataToLocate(getActivity(), "weiboNickName", null); // QuanleimuApplication.setWeiboAccessToken(null); // Weibo.getInstance().setAccessToken(null); // Weibo.getInstance().setRequestToken(null); // Weibo.getInstance().setupConsumerConfig("", ""); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(""); // } // }); // builder.create().show(); // } // else{ // Weibo weibo = Weibo.getInstance(); // weibo.setupConsumerConfig(QuanleimuApplication.kWBBaixingAppKey, QuanleimuApplication.kWBBaixingAppSecret); // weibo.setRedirectUrl("http://www.baixing.com"); //// weibo.authorize((BaseActivity)this.getContext(), new AuthDialogListener()); // WeiboParameters parameters=new WeiboParameters(); // parameters.add("forcelogin", "true"); // Utility.setAuthorization(new Oauth2AccessTokenHeader()); // AuthDialogListener lsn = new AuthDialogListener(getActivity(), new AuthDialogListener.AuthListener(){ // @Override // public void onComplete(){ // String nick = (String)Helper.loadDataFromLocate(getActivity(), "weiboNickName"); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(nick); // } // }); // weibo.dialog(getActivity(), // parameters, lsn); // lsn.setInAuthrize(true); // } // } /* final View root = getView(); // 签名档 if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlMark)).getId()) { pushFragment(new MarkLableFragment(), null ); } // 清空缓存 else if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlClearCache)).getId()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_title_info) .setMessage(R.string.dialog_message_confirm_clear_cache) .setNegativeButton(R.string.no, null) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String[] files = getActivity().fileList(); for(int i=0;i<files.length;i++){ String file_path = files[i]; getActivity().deleteFile(file_path); } QuanleimuApplication.getApplication().ClearCache(); //清空签名档 // ((TextView)root.findViewById(R.id.personMark)).setText(""); } }); builder.create().show(); } */ }
public void onClick(View v) { switch (v.getId()) { case R.id.setFlowOptimize: showFlowOptimizeDialog(); break; case R.id.setBindID: if (user == null || user.getPhone() == null || user.getPhone().equals("")) { Bundle bundle = createArguments(null, "用户中心"); pushFragment(new LoginFragment(), bundle); } else { //TODO jiawu 加入确认退出过程 logoutAction(); refreshUI(getView()); } break; case R.id.setCheckUpdate: checkNewVersion(); break; case R.id.setAbout: pushFragment(new AboutUsFragment(), null); break; case R.id.setFeedback: pushFragment(new FeedbackFragment(), createArguments(null, null)); break; default: Toast.makeText(getAppContext(), "no action", 1).show(); break; } // 手机号码 // if(v.getId() == R.id.rlWeibo){ // if(QuanleimuApplication.getWeiboAccessToken() != null){ // AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // builder.setTitle("提示:") // .setMessage("是否解除绑定?") // .setNegativeButton("否", null) // .setPositiveButton("是", // new DialogInterface.OnClickListener() { // // @Override // public void onClick(DialogInterface dialog, // int which) { // // Helper.saveDataToLocate(getActivity(), "weiboToken", null); // Helper.saveDataToLocate(getActivity(), "weiboNickName", null); // QuanleimuApplication.setWeiboAccessToken(null); // Weibo.getInstance().setAccessToken(null); // Weibo.getInstance().setRequestToken(null); // Weibo.getInstance().setupConsumerConfig("", ""); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(""); // } // }); // builder.create().show(); // } // else{ // Weibo weibo = Weibo.getInstance(); // weibo.setupConsumerConfig(QuanleimuApplication.kWBBaixingAppKey, QuanleimuApplication.kWBBaixingAppSecret); // weibo.setRedirectUrl("http://www.baixing.com"); //// weibo.authorize((BaseActivity)this.getContext(), new AuthDialogListener()); // WeiboParameters parameters=new WeiboParameters(); // parameters.add("forcelogin", "true"); // Utility.setAuthorization(new Oauth2AccessTokenHeader()); // AuthDialogListener lsn = new AuthDialogListener(getActivity(), new AuthDialogListener.AuthListener(){ // @Override // public void onComplete(){ // String nick = (String)Helper.loadDataFromLocate(getActivity(), "weiboNickName"); // ((TextView)findViewById(R.id.tvWeiboNick)).setText(nick); // } // }); // weibo.dialog(getActivity(), // parameters, lsn); // lsn.setInAuthrize(true); // } // } /* final View root = getView(); // 签名档 if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlMark)).getId()) { pushFragment(new MarkLableFragment(), null ); } // 清空缓存 else if (v.getId() == ((RelativeLayout) root.findViewById(R.id.rlClearCache)).getId()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_title_info) .setMessage(R.string.dialog_message_confirm_clear_cache) .setNegativeButton(R.string.no, null) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String[] files = getActivity().fileList(); for(int i=0;i<files.length;i++){ String file_path = files[i]; getActivity().deleteFile(file_path); } QuanleimuApplication.getApplication().ClearCache(); //清空签名档 // ((TextView)root.findViewById(R.id.personMark)).setText(""); } }); builder.create().show(); } */ }
diff --git a/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java b/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java index 95870ed2d..779eb8b5c 100644 --- a/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java +++ b/atlas-web/src/main/java/ae3/service/AtlasBitIndexQueryService.java @@ -1,599 +1,599 @@ package ae3.service; import com.google.common.collect.*; import it.uniroma3.mat.extendedset.ConciseSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.gxa.efo.Efo; import uk.ac.ebi.gxa.index.StatisticsStorageFactory; import uk.ac.ebi.gxa.index.builder.IndexBuilder; import uk.ac.ebi.gxa.statistics.*; import uk.ac.ebi.gxa.utils.Pair; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.*; import static com.google.common.collect.HashMultiset.create; import static com.google.common.collect.Maps.newHashMap; import static uk.ac.ebi.gxa.exceptions.LogUtil.createUnexpected; /** * This class provides bioentity expression statistics query service: * - manages the index storage management and interaction with IndexBuider service * - delegates statistics queries to StatisticsQueryUtils */ public class AtlasBitIndexQueryService implements AtlasStatisticsQueryService { final private Logger log = LoggerFactory.getLogger(getClass()); // Handler for the BitIndex builder private IndexBuilder indexBuilder; // Bitindex Object which is de-serialized from indexFileName in atlasIndexDir private StatisticsStorage statisticsStorage; private File atlasIndexDir; private String indexFileName; // Used for finding children for query efo's private Efo efo; public AtlasBitIndexQueryService(String indexFileName) { this.indexFileName = indexFileName; } public void setAtlasIndex(File atlasIndexDir) { this.atlasIndexDir = atlasIndexDir; } public void setIndexBuilder(IndexBuilder indexBuilder) { this.indexBuilder = indexBuilder; indexBuilder.registerIndexBuildEventHandler(this); } public void setStatisticsStorage(StatisticsStorage statisticsStorage) { this.statisticsStorage = statisticsStorage; } public void setEfo(Efo efo) { this.efo = efo; } /** * Index rebuild notification handler - after bit index is re-built, de-serialize it into statisticsStorage and re-populate statTypeToEfoToScores cache */ public void onIndexBuildFinish() { StatisticsStorageFactory statisticsStorageFactory = new StatisticsStorageFactory(indexFileName); statisticsStorageFactory.setAtlasIndex(atlasIndexDir); try { statisticsStorage = statisticsStorageFactory.createStatisticsStorage(); } catch (IOException ioe) { String errMsg = "Failed to create statisticsStorage from " + new File(atlasIndexDir.getAbsolutePath(), indexFileName); log.error(errMsg, ioe); throw createUnexpected(errMsg, ioe); } } public void onIndexBuildStart() { // Nothing to do here } /** * Destructor called by Spring * * @throws Exception */ public void destroy() throws Exception { if (indexBuilder != null) indexBuilder.unregisterIndexBuildEventHandler(this); } /** * @param attribute * @param bioEntityId * @param statType * @return Experiment count for statisticsType, attributes and bioEntityId */ public Integer getExperimentCountsForBioEntity( final Attribute attribute, final Integer bioEntityId, final StatisticsType statType) { return getExperimentCountsForBioEntity(attribute, bioEntityId, statType, null, null); } /** * @param attribute * @param bioEntityId * @param statType * @param bioEntityIdRestrictionSet * @param scoresCache * @return Experiment count for statisticsType, attributes and bioEntityId */ public Integer getExperimentCountsForBioEntity( final Attribute attribute, final Integer bioEntityId, final StatisticsType statType, Set<Integer> bioEntityIdRestrictionSet, Map<StatisticsType, HashMap<String, Multiset<Integer>>> scoresCache) { if (bioEntityIdRestrictionSet == null) { // By default restrict the experiment count query to bioEntityId bioEntityIdRestrictionSet = Collections.singleton(bioEntityId); } StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(bioEntityIdRestrictionSet, statType); statsQuery.and(getStatisticsOrQuery(Collections.singletonList(attribute), statType, 1)); Multiset<Integer> scores = StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null); // Cache bioEntityIdRestrictionSet's scores for efvOrEfo - this cache will be re-used in heatmaps for rows other than the first one if (scoresCache != null) { scoresCache.get(statType).put(attribute.getValue(), scores); } if (scores != null) { long time = System.currentTimeMillis(); int expCountForBioEntity = scores.count(bioEntityId); if (expCountForBioEntity > 0) { log.debug(statType + " " + attribute.getValue() + " expCountForBioEntity: " + bioEntityId + " = " + expCountForBioEntity + " got in: " + (System.currentTimeMillis() - time) + " ms"); } return expCountForBioEntity; } return 0; } /** * @param orAttributes * @param statType * @param minExperiments minimum number of experiments restriction for this clause * @return StatisticsQueryOrConditions, including children of all efo's in orAttributes */ public StatisticsQueryOrConditions<StatisticsQueryCondition> getStatisticsOrQuery( final List<Attribute> orAttributes, final StatisticsType statType, int minExperiments) { List<Attribute> efoPlusChildren = includeEfoChildren(orAttributes); return StatisticsQueryUtils.getStatisticsOrQuery(efoPlusChildren, statType, minExperiments, statisticsStorage); } /** * @param orAttributes * @return List containing all (afv and efo) attributes in orAttributes, plus the children of all efo's in orAttributes */ private List<Attribute> includeEfoChildren(List<Attribute> orAttributes) { // LinkedHashSet for maintaining order of entry - order of processing attributes may be important // in multi-Attribute queries for sorted lists of experiments for the gene page Set<Attribute> attrsPlusChildren = new LinkedHashSet<Attribute>(); for (Attribute attr : orAttributes) attrsPlusChildren.addAll(attr.getAttributeAndChildren(efo)); return new ArrayList<Attribute>(attrsPlusChildren); } /** * http://stackoverflow.com/questions/3029151/find-top-n-elements-in-a-multiset-from-google-collections * * @param multiset * @param <T> * @return */ private static <T> ImmutableList<Multiset.Entry<T>> sortedByCount(Multiset<T> multiset) { Ordering<Multiset.Entry<T>> countComp = new Ordering<Multiset.Entry<T>>() { public int compare(Multiset.Entry<T> e1, Multiset.Entry<T> e2) { return e2.getCount() - e1.getCount(); } }; return countComp.immutableSortedCopy(multiset.entrySet()); } /** * http://stackoverflow.com/questions/3029151/find-top-n-elements-in-a-multiset-from-google-collections * * @param multiset * @param min * @param max * @param <T> * @return */ private static <T> ImmutableList<Multiset.Entry<T>> getEntriesBetweenMinMaxFromListSortedByCount(Multiset<T> multiset, int min, int max) { ImmutableList<Multiset.Entry<T>> sortedByCount = sortedByCount(multiset); int totalResults = sortedByCount.size(); if (min < 0 || min > totalResults) min = 0; if (totalResults > max) { return sortedByCount.subList(min, max); } return sortedByCount.subList(min, totalResults); } /** * @param statsQuery * @param minPos * @param rows * @param bioEntityIdRestrictionSet Set of BioEntity ids to restrict the query before sorting * @param sortedBioEntitiesChunk - a chunk of the overall sorted (by experiment counts - in desc order) list of bioentities, * starting from 'minPos' and containing maximums 'rows' bioentities * @return Pair<The overall number of bioentities for which counts exist in statsQuery, total experiemnt count for returned genes> */ public Pair<Integer, Integer> getSortedBioEntities( final StatisticsQueryCondition statsQuery, final int minPos, final int rows, final Set<Integer> bioEntityIdRestrictionSet, List<Integer> sortedBioEntitiesChunk) { long timeStart = System.currentTimeMillis(); Multiset<Integer> countsForConditions = StatisticsQueryUtils.intersect(StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null), bioEntityIdRestrictionSet); log.debug("Intersected " + countsForConditions.entrySet().size() + " bioentities' experiment counts with " + bioEntityIdRestrictionSet.size() + " restriction bioeentities in " + (System.currentTimeMillis() - timeStart) + " ms"); log.debug("getSortedBioEntities() bit index query: " + statsQuery.prettyPrint()); log.info("getSortedBioEntities() query returned " + countsForConditions.elementSet().size() + " bioentities with counts present in : " + (System.currentTimeMillis() - timeStart) + " ms"); List<Multiset.Entry<Integer>> sortedCounts = getEntriesBetweenMinMaxFromListSortedByCount(countsForConditions, minPos, minPos + rows); int totalExpCount = 0; for (Multiset.Entry<Integer> entry : sortedCounts) { sortedBioEntitiesChunk.add(entry.getElement()); totalExpCount += entry.getCount(); } log.debug("Total experiment count: " + totalExpCount); return Pair.create(countsForConditions.elementSet().size(), totalExpCount); } /** * @param efoTerm * @return Set of EfvAttributes corresponding to efoTerm. Note that efo's map to ef-efv-experiment triples. However, this method * is used in AtlasStructuredQueryService for populating list view, which for efo queries shows ef-efvs those efos map to and * _all_ experiments in which these ef-efvs have expressions. In other words, we don't restrict experiments shown in the list view * to just those in query efo->ef-efv-experiment mapping. */ public Set<EfvAttribute> getAttributesForEfo(String efoTerm) { Set<EfvAttribute> attrsForEfo = new HashSet<EfvAttribute>(); Map<ExperimentInfo, Set<EfvAttribute>> expToAttrsForEfo = statisticsStorage.getMappingsForEfo(efoTerm); for (Collection<EfvAttribute> expToAttrIndexes : expToAttrsForEfo.values()) { attrsForEfo.addAll(expToAttrIndexes); } return attrsForEfo; } /** * @param efoTerm * @return the total count of experiment-attribute mappings for efoTerm. A measure of how expensive a given efoTerm will be * to search against bit index. Currently used just for logging. */ public int getMappingsCountForEfo(String efoTerm) { int count = 0; Map<ExperimentInfo, Set<EfvAttribute>> expToAttrsForEfo = statisticsStorage.getMappingsForEfo(efoTerm); for (Collection<EfvAttribute> expToAttrIndexes : expToAttrsForEfo.values()) { count += expToAttrIndexes.size(); } return count; } /** * @param bioEntityId Bioentity of interest * @param attribute Attribute * @param fromRow Used for paginating of experiment plots on gene page * @param toRow ditto * @param statType StatisticsType * @return List of Experiments sorted by pVal/tStat ranks from best to worst */ public List<ExperimentResult> getExperimentsSortedByPvalueTRank( final Integer bioEntityId, final Attribute attribute, int fromRow, int toRow, final StatisticsType statType) { List<Attribute> attrs; if (attribute.isEmpty()) { attrs = new ArrayList<Attribute>(); attrs.addAll(getScoringEfsForBioEntity(bioEntityId, statType, null)); } else { attrs = Collections.singletonList(attribute); } StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(bioEntityId), statType); statsQuery.and(getStatisticsOrQuery(attrs, statType, 1)); // retrieve experiments sorted by pValue/tRank for statsQuery // Map: experiment id -> ExperimentInfo (used in getBestExperiments() for better than List efficiency of access) Map<Long, ExperimentResult> bestExperimentsMap = getBestExperiments(statsQuery); List<ExperimentResult> bestExperiments = new ArrayList<ExperimentResult>(bestExperimentsMap.values()); // Sort bestExperiments by best pVal/tStat ranks first Collections.sort(bestExperiments, new Comparator<ExperimentResult>() { public int compare(ExperimentResult e1, ExperimentResult e2) { return e1.getPValTStatRank().compareTo(e2.getPValTStatRank()); } }); // Extract the correct chunk (Note that if toRow == fromRow == -1, the whole of bestExperiments is returned) int maxSize = bestExperiments.size(); if (fromRow == -1) fromRow = 0; if (toRow == -1 || toRow > maxSize) toRow = maxSize; List<ExperimentResult> exps = bestExperiments.subList(fromRow, toRow); log.debug("Sorted experiments: "); for (ExperimentResult exp : exps) { log.debug(exp.getAccession() + ": pval=" + exp.getPValTStatRank().getPValue() + "; tStat rank: " + exp.getPValTStatRank().getTStatRank() + "; highest ranking ef: " + exp.getHighestRankAttribute()); } return exps; } /** * @param bioEntityId * @param statType * @param ef * @return list all efs for which bioEntityId has statType expression in at least one experiment */ public List<EfAttribute> getScoringEfsForBioEntity(final Integer bioEntityId, final StatisticsType statType, @Nullable final String ef) { long timeStart = System.currentTimeMillis(); List<EfAttribute> scoringEfs = new ArrayList<EfAttribute>(); if (bioEntityId != null) { Set<EfAttribute> scoringEfAttrs = statisticsStorage.getScoringEfAttributesForBioEntity(bioEntityId, statType); for (EfAttribute efAttr : scoringEfAttrs) { if (efAttr != null && (ef == null || "".equals(ef) || ef.equals(efAttr.getEf()))) { scoringEfs.add(new EfAttribute(efAttr.getEf())); } } } log.debug("getScoringEfsForBioEntity() returned " + scoringEfs.size() + " efs for bioEntityId: " + bioEntityId + " in: " + (System.currentTimeMillis() - timeStart) + " ms"); return scoringEfs; } /** * @param bioEntityId * @param statType * @return list all efs for which bioEntityId has statType expression in at least one experiment */ public List<EfvAttribute> getScoringEfvsForBioEntity(final Integer bioEntityId, final StatisticsType statType) { long timeStart = System.currentTimeMillis(); List<EfvAttribute> scoringEfvs = new ArrayList<EfvAttribute>(); if (bioEntityId != null) { Set<EfvAttribute> scoringEfvIndexes = statisticsStorage.getScoringEfvAttributesForBioEntity(bioEntityId, statType); for (EfvAttribute efv : scoringEfvIndexes) { if (efv.getEfv() != null && !efv.getEfv().isEmpty()) { scoringEfvs.add(efv); } } } log.debug("getScoringEfsForBioEntity() returned " + scoringEfvs.size() + " efs for bioEntityId: " + bioEntityId + " in: " + (System.currentTimeMillis() - timeStart) + " ms"); return scoringEfvs; } /** * @param attribute * @param bioEntityId * @param statType * @return unsorted list of experiments for which bioEntityId has statType expression for ef attr */ public List<ExperimentInfo> getExperimentsForBioEntityAndAttribute(Integer bioEntityId, @Nullable EfAttribute attribute, StatisticsType statType) { List<ExperimentInfo> exps = new ArrayList<ExperimentInfo>(); // Note that if ef == null, this method returns list of experiments across all efs for which this bioentity has up/down exp counts if (bioEntityId != null) { return new ArrayList<ExperimentInfo>(statisticsStorage.getExperimentsForBioEntityAndAttribute(attribute, bioEntityId, statType)); } return exps; } /** * @param bioEntityIds * @param statType * @param autoFactors set of factors of interest * @param attrCounts if not null, populated by this method. Map: attribute Index -> (non-zero) experiment counts * @param scoringEfos if not null, populated by this method. Set of Efo terms with non-zero experiment counts */ private void collectScoringAttributes(Set<Integer> bioEntityIds, StatisticsType statType, Collection<String> autoFactors, @Nullable Multiset<EfvAttribute> attrCounts, @Nullable Set<String> scoringEfos) { for (EfvAttribute efvAttr : statisticsStorage.getAllEfvAttributes(statType)) { if ((autoFactors != null && !autoFactors.contains(efvAttr.getEf())) || efvAttr.getEfv() == null) { continue; // skip attribute if its factor is not of interest or it's an ef-only attribute } StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(bioEntityIds, statType); statsQuery.and(getStatisticsOrQuery(Collections.<Attribute>singletonList(efvAttr), statType, 1)); Set<ExperimentInfo> scoringExps = new HashSet<ExperimentInfo>(); StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, scoringExps); if (scoringExps.size() > 0) { // at least one bioEntityId in bioEntityIds had an experiment count > 0 for attr if (attrCounts != null) attrCounts.add(efvAttr, scoringExps.size()); for (ExperimentInfo exp : scoringExps) { Set<String> efoTerms = statisticsStorage.getEfoTerms(efvAttr, exp); if (scoringEfos != null) scoringEfos.addAll(efoTerms); else log.debug("Skipping efo: {} for attr: {} and exp: {}", new Object[]{efoTerms, efvAttr, exp}); } } } } /** * @param bioEntityIds * @param statType * @return Set of efo's with non-zero statType experiment counts for bioEntityIds */ public Set<String> getScoringEfosForBioEntities(Set<Integer> bioEntityIds, StatisticsType statType) { Set<String> scoringEfos = new HashSet<String>(); collectScoringAttributes(bioEntityIds, statType, null, null, scoringEfos); return scoringEfos; } /** * @param bioEntityIds * @param statType * @param autoFactors set of factors of interest * @return Serted set of non-zero experiment counts (for at least one of bioEntityIds and statType) per efv (note: not efo) attribute */ public List<Multiset.Entry<EfvAttribute>> getScoringAttributesForBioEntities(Set<Integer> bioEntityIds, StatisticsType statType, Collection<String> autoFactors) { long timeStart = System.currentTimeMillis(); Multiset<EfvAttribute> attrCounts = create(); collectScoringAttributes(bioEntityIds, statType, autoFactors, attrCounts, null); List<Multiset.Entry<EfvAttribute>> sortedAttrCounts = getEntriesBetweenMinMaxFromListSortedByCount(attrCounts, 0, attrCounts.entrySet().size()); log.debug("Retrieved " + sortedAttrCounts.size() + " sorted scoring attributes for statType: " + statType + " and bioentity ids: (" + bioEntityIds + ") in " + (System.currentTimeMillis() - timeStart) + "ms"); return sortedAttrCounts; } /** * @param bioEntityId * @param attribute * @param statType * @return Set of Experiments in which bioEntityId-ef-efv have statType expression */ public Set<ExperimentInfo> getScoringExperimentsForBioEntityAndAttribute( final Integer bioEntityId, @Nonnull Attribute attribute, final StatisticsType statType) { StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(Collections.singleton(bioEntityId), statType); statsQuery.and(getStatisticsOrQuery(Collections.<Attribute>singletonList(attribute), statType, 1)); Set<ExperimentInfo> scoringExps = new HashSet<ExperimentInfo>(); StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, scoringExps); return scoringExps; } /** * @param attribute * @param allExpsToAttrs Map: ExperimentInfo -> Set<Attribute> to which mappings for an Attribute are to be added. */ public void getAttributeToExperimentMappings( final Attribute attribute, Map<ExperimentInfo, Set<EfAttribute>> allExpsToAttrs) { attribute.getAttributeToExperimentMappings(statisticsStorage, allExpsToAttrs); } /** * @param statType * @return Collection of unique experiments with expressions for statType */ public Collection<ExperimentInfo> getScoringExperiments(StatisticsType statType) { return statisticsStorage.getScoringExperiments(statType); } /** * @param attribute * @param statType * @return the amount of bioentities with expression statType for efv attribute */ public int getBioEntityCountForEfvAttribute(EfvAttribute attribute, StatisticsType statType) { return statisticsStorage.getBioEntityCountForAttribute(attribute, statType); } /** * @param attribute * @param statType * @return the amount of bioentities with expression statType for efo attribute */ public int getBioEntityCountForEfoAttribute(Attribute attribute, StatisticsType statType) { StatisticsQueryCondition statsQuery = new StatisticsQueryCondition(statType); statsQuery.and(getStatisticsOrQuery(Collections.singletonList(attribute), statType, 1)); return StatisticsQueryUtils.getExperimentCounts(statsQuery, statisticsStorage, null).entrySet().size(); } /** * Populate bestExperimentsSoFar with an (unsorted) list of experiments with best pval/tstat rank, for statisticsQuery * * @param statisticsQuery * @return (unordered) Map of experiment id-> best pval/tstat rank for that experiment as a result of * statisticsQuery against statisticsStorage */ private Map<Long, ExperimentResult> getBestExperiments(StatisticsQueryCondition statisticsQuery) { Map<Long, ExperimentResult> bestExperimentsMap = newHashMap(); getBestExperimentsRecursive(statisticsQuery, bestExperimentsMap); return bestExperimentsMap; } /** * Populate bestExperimentsSoFar with an (unordered) Map of experiment id-> best pval/tstat rank for that * experiment as a result of statisticsQuery against statisticsStorage * * @param statisticsQuery * @param bestExperimentsSoFar */ private void getBestExperimentsRecursive( StatisticsQueryCondition statisticsQuery, Map<Long, ExperimentResult> bestExperimentsSoFar) { Set<StatisticsQueryOrConditions<StatisticsQueryCondition>> andStatisticsQueryConditions = statisticsQuery.getConditions(); if (andStatisticsQueryConditions.isEmpty()) { // End of recursion Set<Integer> bioEntityIdRestrictionSet = statisticsQuery.getBioEntityIdRestrictionSet(); - Set<EfvAttribute> attributes = statisticsQuery.getAttributes(); + Set<EfAttribute> attributes = statisticsQuery.getAttributes(); Set<ExperimentInfo> experiments = statisticsQuery.getExperiments(); - for (EfvAttribute attr : attributes) { + for (EfAttribute attr : attributes) { SortedMap<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenes = statisticsStorage.getPvalsTStatRanksForAttribute(attr, statisticsQuery.getStatisticsType()); if (pValToExpToGenes != null) { for (Map.Entry<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenesEntry : pValToExpToGenes.entrySet()) { Map<ExperimentInfo, ConciseSet> expToGenes = pValToExpToGenesEntry.getValue(); if (expToGenes != null) { for (Map.Entry<ExperimentInfo, ConciseSet> expToGenesEntry : expToGenes.entrySet()) { if (experiments.isEmpty() || experiments.contains(expToGenesEntry.getKey())) { if (StatisticsQueryUtils.containsAtLeastOne(expToGenesEntry.getValue(), bioEntityIdRestrictionSet)) { // If best experiments are collected for an (OR) group of genes, pVal/tStat // for any of these genes will be considered here ExperimentResult expCandidate = new ExperimentResult(expToGenesEntry.getKey(), attr, pValToExpToGenesEntry.getKey()); tryAddOrReplaceExperiment(expCandidate, bestExperimentsSoFar); } } } } } } } } else { // We only expect one 'AND' condition with set of orConditions inside StatisticsQueryOrConditions<StatisticsQueryCondition> orConditions = andStatisticsQueryConditions.iterator().next(); if (orConditions != null) { for (StatisticsQueryCondition orCondition : orConditions.getConditions()) { // Pass gene restriction set down to orCondition orCondition.setBioEntityIdRestrictionSet(orConditions.getBioEntityIdRestrictionSet()); getBestExperimentsRecursive(orCondition, bestExperimentsSoFar); } } } } /** * If exp cannot be found in exps, add it to exps * If it can be found and its pVal/tStat ranks are worse the one is exps, replace it in exps * * @param exp * @param exps */ private static void tryAddOrReplaceExperiment(ExperimentResult exp, Map<Long, ExperimentResult> exps) { long expId = exp.getExperimentId(); ExperimentResult existingExp = exps.get(expId); if (existingExp != null) { if (exp.getPValTStatRank().compareTo(existingExp.getPValTStatRank()) < 0) { exps.put(expId, exp); } } else { exps.put(expId, exp); } } }
false
true
private void getBestExperimentsRecursive( StatisticsQueryCondition statisticsQuery, Map<Long, ExperimentResult> bestExperimentsSoFar) { Set<StatisticsQueryOrConditions<StatisticsQueryCondition>> andStatisticsQueryConditions = statisticsQuery.getConditions(); if (andStatisticsQueryConditions.isEmpty()) { // End of recursion Set<Integer> bioEntityIdRestrictionSet = statisticsQuery.getBioEntityIdRestrictionSet(); Set<EfvAttribute> attributes = statisticsQuery.getAttributes(); Set<ExperimentInfo> experiments = statisticsQuery.getExperiments(); for (EfvAttribute attr : attributes) { SortedMap<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenes = statisticsStorage.getPvalsTStatRanksForAttribute(attr, statisticsQuery.getStatisticsType()); if (pValToExpToGenes != null) { for (Map.Entry<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenesEntry : pValToExpToGenes.entrySet()) { Map<ExperimentInfo, ConciseSet> expToGenes = pValToExpToGenesEntry.getValue(); if (expToGenes != null) { for (Map.Entry<ExperimentInfo, ConciseSet> expToGenesEntry : expToGenes.entrySet()) { if (experiments.isEmpty() || experiments.contains(expToGenesEntry.getKey())) { if (StatisticsQueryUtils.containsAtLeastOne(expToGenesEntry.getValue(), bioEntityIdRestrictionSet)) { // If best experiments are collected for an (OR) group of genes, pVal/tStat // for any of these genes will be considered here ExperimentResult expCandidate = new ExperimentResult(expToGenesEntry.getKey(), attr, pValToExpToGenesEntry.getKey()); tryAddOrReplaceExperiment(expCandidate, bestExperimentsSoFar); } } } } } } } } else { // We only expect one 'AND' condition with set of orConditions inside StatisticsQueryOrConditions<StatisticsQueryCondition> orConditions = andStatisticsQueryConditions.iterator().next(); if (orConditions != null) { for (StatisticsQueryCondition orCondition : orConditions.getConditions()) { // Pass gene restriction set down to orCondition orCondition.setBioEntityIdRestrictionSet(orConditions.getBioEntityIdRestrictionSet()); getBestExperimentsRecursive(orCondition, bestExperimentsSoFar); } } } }
private void getBestExperimentsRecursive( StatisticsQueryCondition statisticsQuery, Map<Long, ExperimentResult> bestExperimentsSoFar) { Set<StatisticsQueryOrConditions<StatisticsQueryCondition>> andStatisticsQueryConditions = statisticsQuery.getConditions(); if (andStatisticsQueryConditions.isEmpty()) { // End of recursion Set<Integer> bioEntityIdRestrictionSet = statisticsQuery.getBioEntityIdRestrictionSet(); Set<EfAttribute> attributes = statisticsQuery.getAttributes(); Set<ExperimentInfo> experiments = statisticsQuery.getExperiments(); for (EfAttribute attr : attributes) { SortedMap<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenes = statisticsStorage.getPvalsTStatRanksForAttribute(attr, statisticsQuery.getStatisticsType()); if (pValToExpToGenes != null) { for (Map.Entry<PTRank, Map<ExperimentInfo, ConciseSet>> pValToExpToGenesEntry : pValToExpToGenes.entrySet()) { Map<ExperimentInfo, ConciseSet> expToGenes = pValToExpToGenesEntry.getValue(); if (expToGenes != null) { for (Map.Entry<ExperimentInfo, ConciseSet> expToGenesEntry : expToGenes.entrySet()) { if (experiments.isEmpty() || experiments.contains(expToGenesEntry.getKey())) { if (StatisticsQueryUtils.containsAtLeastOne(expToGenesEntry.getValue(), bioEntityIdRestrictionSet)) { // If best experiments are collected for an (OR) group of genes, pVal/tStat // for any of these genes will be considered here ExperimentResult expCandidate = new ExperimentResult(expToGenesEntry.getKey(), attr, pValToExpToGenesEntry.getKey()); tryAddOrReplaceExperiment(expCandidate, bestExperimentsSoFar); } } } } } } } } else { // We only expect one 'AND' condition with set of orConditions inside StatisticsQueryOrConditions<StatisticsQueryCondition> orConditions = andStatisticsQueryConditions.iterator().next(); if (orConditions != null) { for (StatisticsQueryCondition orCondition : orConditions.getConditions()) { // Pass gene restriction set down to orCondition orCondition.setBioEntityIdRestrictionSet(orConditions.getBioEntityIdRestrictionSet()); getBestExperimentsRecursive(orCondition, bestExperimentsSoFar); } } } }
diff --git a/src/cps450/CodeGenerator.java b/src/cps450/CodeGenerator.java index c3a6874..f990705 100644 --- a/src/cps450/CodeGenerator.java +++ b/src/cps450/CodeGenerator.java @@ -1,571 +1,571 @@ package cps450; import java.io.File; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Stack; import java.io.PrintWriter; import cps450.oodle.analysis.*; import cps450.oodle.node.*; public class CodeGenerator extends DepthFirstAdapter { PrintWriter writer; int ifStatementCount = 0; Stack<Integer> ifStatementCounts; int loopStatementCount; Stack<Integer> loopStatementCounts; int stringCount = 0; int callCount = 0; Hashtable<String, ClassDeclaration> classTable; Hashtable<Node, Type> typeDecorations; MethodDeclaration currentMethodDeclaration = null; String currentClassName; ClassDeclaration currentClassDeclaration = null; public CodeGenerator(PrintWriter _writer, Hashtable<String, ClassDeclaration> _classTable, Hashtable<Node, Type> _typeDecorations) { super(); writer = _writer; ifStatementCounts = new Stack<Integer>(); loopStatementCounts = new Stack<Integer>(); classTable = _classTable; typeDecorations = _typeDecorations; } private void emit(String sourceLine) { writer.println(sourceLine); } private void emitOodleStatement(Token token) { emit(""); emit("# " + token.getLine() + ": " + SourceHolder.instance().getLine(token.getLine()-1)); } private void emitStringExpressionFor(String text) { String label = "strlit" + stringCount; emit(".data"); emit(label + ": .string " + text); emit(".text"); emit("pushl $" + label); emit("call string_fromlit"); emit("movl %eax, (%esp) # Cleanup parameter and push return value all at once"); stringCount++; } public String getMethodLabel(String className, String methodName) { if (!(className.equals("in") || className.equals("out"))) { return className + "_" + methodName; } else { return methodName; } } public void emitClassInstantiationExpressionFor(ClassDeclaration klass) { // Allocate space for the object // - 2 * 4 bytes reserved + 4 * instance variable count emit("# Instantiate object"); emit("pushl $4"); // Size of each reserved element is 4 bytes emit("pushl $" + (2 + klass.getInstanceVariableCount())); // Total allocated elements emit("call calloc"); emit("addl $8, %esp"); emit("pushl %eax"); } /* * Start the generated with the predefined data directives. * @see cps450.oodle.analysis.DepthFirstAdapter#inAStart(cps450.oodle.node.AStart) */ @Override public void inAStart(AStart node) { emit(".data"); emit(".comm _out, 4, 4"); emit(".comm _in, 4, 4"); emit(".comm errorLine, 4, 4"); } @Override public void outStart(Start node) { emit(""); emit(".text"); emit(".global main"); emit("main:"); // Instantiate globals emitClassInstantiationExpressionFor(classTable.get("Reader")); emit("popl _in"); emitClassInstantiationExpressionFor(classTable.get("Writer")); emit("popl _out"); // Instantiate the main class emitClassInstantiationExpressionFor(currentClassDeclaration); // Self argument is left on the stack from the instantiation expression emit("call " + getMethodLabel(currentClassName, "start")); emit("addl $4, %esp # Cleanup method argument"); // End the program emit("push $0"); emit("call exit"); emit(""); emit("# Global helpers"); emit(".text"); emit("__npe__:"); emit("pushl _out"); - emitStringExpressionFor("\"The little gremlin running your program is scratching his head wondering how he is supposed to look up a method on a null object at line:\""); - emit("call Writer_writeln"); + emitStringExpressionFor("\"The little gremlin running your program is scratching his head wondering how he is supposed to look up a method on a null object at line: \""); + emit("call Writer_write"); //emit("addl $8, %esp"); emit("pushl _out"); emit("pushl errorLine"); emit("call Writer_writeint"); //emit("addl $8, %esp"); emit("pushl $1"); emit("call exit"); } /* * Start the generated with the predefined data directives. * @see cps450.oodle.analysis.DepthFirstAdapter#inAClassDef(cps450.oodle.node.AClassDef) */ @Override public void inAClassDef(AClassDef node) { currentClassName = node.getBeginName().getText(); currentClassDeclaration = classTable.get(node.getBeginName().getText()); } /* * Generate assembly for addition expressions. * @see cps450.oodle.analysis.DepthFirstAdapter#outAAddExpression(cps450.oodle.node.AAddExpression) */ @Override public void outAAddExpression(AAddExpression node) { emit("popl %eax # AddExpression"); emit("popl %ebx"); if (node.getOperator() instanceof APlusOperator) { emit("addl %eax, %ebx"); } else if (node.getOperator() instanceof AMinusOperator) { emit("subl %eax, %ebx"); } emit("pushl %ebx # Store AddExpression result"); } /* * Generate assembly for And expressions. * @see cps450.oodle.analysis.DepthFirstAdapter#outAAndExpression(cps450.oodle.node.AAndExpression) */ @Override public void outAAndExpression(AAndExpression node) { emit("popl %eax # AndExpression"); emit("popl %ebx"); emit("andl %ebx, %eax"); emit("pushl %eax # Store AndExpression result"); } /* * Output a comment with the oodle source. * @see cps450.oodle.analysis.DepthFirstAdapter#inAAssignmentStatement(cps450.oodle.node.AAssignmentStatement) */ @Override public void inAAssignmentStatement(AAssignmentStatement node) { emitOodleStatement(node.getId()); } /* * Generate assembly for assignment statements. * @see cps450.oodle.analysis.DepthFirstAdapter#outAAssignmentStatement(cps450.oodle.node.AAssignmentStatement) */ @Override public void outAAssignmentStatement(AAssignmentStatement node) { emit("popl %eax # AssignmentStatement"); String name = node.getId().getText(); VariableDeclaration local = currentMethodDeclaration.getVariable(name); if (local != null) { emit("movl %eax, " + local.getStackOffset() + "(%ebp) # Move value to local variable '" + name + "'"); } else { VariableDeclaration instance = currentClassDeclaration.getVariable(name); if (instance != null) { VariableDeclaration self = currentMethodDeclaration.getVariable("me"); emit("movl " + self.getStackOffset() + "(%ebp), %ebx # Get reference to self"); emit("movl %eax, " + instance.getInstanceOffset() +"(%ebx) # Move value to Klass#" + name); } else { // Global variable emit("movl %eax, _" + name); } } } /* * Generate assembly to push the self argument before a method call * @see cps450.oodle.analysis.DepthFirstAdapter#inACallExpression(cps450.oodle.node.ACallExpression) */ @Override public void inACallExpression(ACallExpression node) { if (node.getObject() == null) { // Method call has implicit callee; pass along the current lexical self VariableDeclaration self = currentMethodDeclaration.getVariable("me"); emit("pushl " + self.getStackOffset() + "(%ebp) # Push reference to self as argument"); } // Else: explicit object callee; self value pushed by the expression evaluation } /* * Generate assembly for the actual calling of the method * @see cps450.oodle.analysis.DepthFirstAdapter#outACallExpression(cps450.oodle.node.ACallExpression) */ @Override public void outACallExpression(ACallExpression node) { String klass = (node.getObject() == null) ? currentClassName : typeDecorations.get(node.getObject()).getName(); String methodName = node.getMethod().getText(); String methodLabel = getMethodLabel(klass, methodName); Integer argCount = node.getArguments().size() + 1; // Offset for the "self" argument // Dynamic null pointer checking emit("cmpl $0, " + (argCount - 1)*4 + "(%esp)"); emit("jne call" + callCount); emit("movl $" + SourceHolder.instance().getLineNumberFor(node.getMethod()) + ", errorLine"); emit("jmp __npe__"); // Call method emit("call" + callCount + ":"); emit("call " + methodLabel); emit("addl $" + ((argCount) * 4) + ", %esp # Clean up the argument values"); emit("pushl %eax # Assume that we got a return value"); callCount++; } @Override public void caseACallExpression(ACallExpression node) { inACallExpression(node); if(node.getObject() != null) { node.getObject().apply(this); } if(node.getMethod() != null) { node.getMethod().apply(this); } { List<PExpression> copy = new ArrayList<PExpression>(node.getArguments()); java.util.Collections.reverse(copy); for(PExpression e : copy) { e.apply(this); } } outACallExpression(node); } /* * Output a comment with the oodle source. * @see cps450.oodle.analysis.DepthFirstAdapter#inACallStatement(cps450.oodle.node.ACallStatement) */ @Override public void inACallStatement(ACallStatement node) { ACallExpression expr = (ACallExpression)node.getExpression(); emitOodleStatement(expr.getMethod()); } /* * Generate assembly to cleanup after the call statements. * @see cps450.oodle.analysis.DepthFirstAdapter#outACallStatement(cps450.oodle.node.ACallStatement) */ @Override public void outACallStatement(ACallStatement node) { emit("popl %eax # Cleanup unused return value in CallStatement"); } /* * Generate assembly for the comparison expressions. * @see cps450.oodle.analysis.DepthFirstAdapter#outAComparisonExpression(cps450.oodle.node.AComparisonExpression) */ @Override public void outAComparisonExpression(AComparisonExpression node) { emit("popl %eax # ComparisonExpression"); emit("popl %ebx"); emit("cmpl %eax, %ebx"); if (node.getOperator() instanceof AEqualOperator) { emit("sete %al # Equal"); } else if (node.getOperator() instanceof AGreaterOperator) { emit("setg %al # Greater"); } else if (node.getOperator() instanceof AGreaterEqualOperator) { emit("setge %al # GreaterOrEqual"); } emit("movzbl %al, %eax"); emit("pushl %eax # Store ComparisonExpression result"); } /* * Generate assembly for a false keyword. * @see cps450.oodle.analysis.DepthFirstAdapter#outAFalseExpression(cps450.oodle.node.AFalseExpression) */ @Override public void outAFalseExpression(AFalseExpression node) { emit("pushl $0 # FalseExpression"); } /* * Generate assembly to evaluate the value of a variable. * @see cps450.oodle.analysis.DepthFirstAdapter#outAIdentifierExpression(cps450.oodle.node.AIdentifierExpression) */ @Override public void outAIdentifierExpression(AIdentifierExpression node) { String name = node.getId().getText(); VariableDeclaration local = currentMethodDeclaration.getVariable(name); if (local != null) { emit("pushl " + local.getStackOffset() + "(%ebp) # Push local variable '" + name + "'"); } else { VariableDeclaration instance = currentClassDeclaration.getVariable(name); if (instance != null) { VariableDeclaration self = currentMethodDeclaration.getVariable("me"); emit("movl " + self.getStackOffset() + "(%ebp), %ebx # Get reference to self"); emit("pushl " + instance.getInstanceOffset() +"(%ebx) # Push value of Klass#" + name); } else { // Global variable emit("pushl _" + name); } } } /* * Output oodle source as comment in assembly. * @see cps450.oodle.analysis.DepthFirstAdapter#inAIfStatement(cps450.oodle.node.AIfStatement) */ @Override public void inAIfStatement(AIfStatement node) { emitOodleStatement(node.getIf()); } /* * Generate the assembly to test the if expression and execute the correct statements. * @see cps450.oodle.analysis.DepthFirstAdapter#outAIfHelper(cps450.oodle.node.AIfHelper) */ @Override public void outAIfHelper(AIfHelper node) { this.ifStatementCounts.push(this.ifStatementCount); this.ifStatementCount++; emit("popl %eax # Get comparison value for IfStatement"); emit("cmpl $0, %eax"); emit("jne _true_statements_" + this.ifStatementCounts.peek()); emit("jmp _false_statements_" + this.ifStatementCounts.peek()); emit("_true_statements_" + this.ifStatementCounts.peek() + ":"); } /* * Generate the code in the middle of the if so we only execute the correct statements. * @see cps450.oodle.analysis.DepthFirstAdapter#outAElseHelper(cps450.oodle.node.AElseHelper) */ @Override public void outAElseHelper(AElseHelper node) { emit("jmp _end_if_statement_" + this.ifStatementCounts.peek()); emit("_false_statements_" + this.ifStatementCounts.peek() + ":"); } /* * Generate the end label for the if statements. * @see cps450.oodle.analysis.DepthFirstAdapter#outAIfStatement(cps450.oodle.node.AIfStatement) */ @Override public void outAIfStatement(AIfStatement node) { emit("_end_if_statement_" + this.ifStatementCounts.peek() + ":"); this.ifStatementCounts.pop(); } /* * Generate assembly to evaluate an integer literal. * @see cps450.oodle.analysis.DepthFirstAdapter#outAIntegerExpression(cps450.oodle.node.AIntegerExpression) */ @Override public void outAIntegerExpression(AIntegerExpression node) { emit("pushl $" + node.getIntlit().getText()); } /* * Output oodle source as a comment. * @see cps450.oodle.analysis.DepthFirstAdapter#inALoopStatement(cps450.oodle.node.ALoopStatement) */ @Override public void inALoopStatement(ALoopStatement node) { emitOodleStatement(node.getLoop()); this.loopStatementCounts.push(this.loopStatementCount); this.loopStatementCount++; emit("_begin_loop_statement_" + this.loopStatementCounts.peek() + ":"); } /* * Generate test expression evaluation in loop statement * @see cps450.oodle.analysis.DepthFirstAdapter#outALoopHelper(cps450.oodle.node.ALoopHelper) */ @Override public void outALoopHelper(ALoopHelper node) { emit("popl %eax # Get comparison value for LoopStatement"); emit("cmpl $0, %eax"); emit("jne _loop_statements_" + this.loopStatementCounts.peek()); emit("jmp _end_loop_statement_" + this.loopStatementCounts.peek()); emit("_loop_statements_" + this.loopStatementCounts.peek() + ":"); } /* * Generate the end label of a loop statement and reset to the beginning of the loop. * @see cps450.oodle.analysis.DepthFirstAdapter#outALoopStatement(cps450.oodle.node.ALoopStatement) */ @Override public void outALoopStatement(ALoopStatement node) { emit("jmp _begin_loop_statement_" + this.loopStatementCounts.peek()); emit("_end_loop_statement_" + this.loopStatementCounts.peek() + ":"); this.loopStatementCounts.pop(); } @Override public void outAMeExpression(AMeExpression node) { VariableDeclaration self = currentMethodDeclaration.getVariable("me"); emit("pushl " + self.getStackOffset() + "(%ebp) # MeExpression"); } /* * Generate assembly labels for a method beginning. * @see cps450.oodle.analysis.DepthFirstAdapter#inAMethodDeclaration(cps450.oodle.node.AMethodDeclaration) */ @Override public void inAMethodDeclaration(AMethodDeclaration node) { currentMethodDeclaration = currentClassDeclaration.getMethod(node.getBeginName().getText()); emit(".text"); String name = node.getBeginName().getText(); emit("\n# Method: " + currentClassName + "#" + name); emit(getMethodLabel(currentClassName, name) + ":"); // Activation record emit("pushl %ebp"); emit("movl %esp, %ebp"); emit("subl $" + ((currentMethodDeclaration.getLocalCount()) * 4) + ", %esp # Make space for local variables"); } /* * Generate the assembly to end the program. * @see cps450.oodle.analysis.DepthFirstAdapter#outAMethodDeclaration(cps450.oodle.node.AMethodDeclaration) */ @Override public void outAMethodDeclaration(AMethodDeclaration node) { // Set return value emit("movl " + currentMethodDeclaration.getVariable(node.getBeginName().getText()).getStackOffset() + "(%ebp), %eax # Set return value"); // Cleanup activation record emit("addl $" + ((node.getVarDeclaration().size() + 1) * 4) + ", %esp # Cleanup local variables"); // Replace old EBP value emit("popl %ebp"); emit("ret"); } /* * Generate assembly to evaluate multiplication and division operations. * @see cps450.oodle.analysis.DepthFirstAdapter#outAMultExpression(cps450.oodle.node.AMultExpression) */ @Override public void outAMultExpression(AMultExpression node) { emit("popl %ebx # MultExpression"); emit("popl %eax"); if (node.getOperator() instanceof AMultOperator) { emit("imull %ebx, %eax"); } else if (node.getOperator() instanceof ADivOperator) { emit("cdq"); emit("idivl %ebx"); } emit("pushl %eax # Store MultExpression result"); } @Override public void outANewObjectExpression(ANewObjectExpression node) { String className = typeDecorations.get(node).getName(); ClassDeclaration klass = classTable.get(className); emitClassInstantiationExpressionFor(klass); } /* * Generate code to save the value of null. * @see cps450.oodle.analysis.DepthFirstAdapter#outANullExpression(cps450.oodle.node.ANullExpression) */ @Override public void outANullExpression(ANullExpression node) { emit("pushl $0"); } /* * Generate code to evaluate and Or expression. * @see cps450.oodle.analysis.DepthFirstAdapter#outAOrExpression(cps450.oodle.node.AOrExpression) */ @Override public void outAOrExpression(AOrExpression node) { emit("popl %eax # AndExpression"); emit("popl %ebx"); emit("orl %ebx, %eax"); emit("pushl %eax # Store AndExpression result"); } @Override public void outAStringExpression(AStringExpression node) { emitStringExpressionFor(node.getStrlit().getText()); } /* * Generate code to evaluate the value of the true expression. * @see cps450.oodle.analysis.DepthFirstAdapter#outATrueExpression(cps450.oodle.node.ATrueExpression) */ @Override public void outATrueExpression(ATrueExpression node) { emit("pushl $1 # TrueExpression"); } /* * Generate assembly code to evaluate unary (+/-) expressions. * @see cps450.oodle.analysis.DepthFirstAdapter#outAUnaryExpression(cps450.oodle.node.AUnaryExpression) */ @Override public void outAUnaryExpression(AUnaryExpression node) { emit("popl %eax # Begin UnaryExpression"); if (node.getOperator() instanceof AMinusOperator) { emit("negl %eax"); } else if (node.getOperator() instanceof ANotOperator) { emit("xorl $1, %eax # Not"); } emit("pushl %eax # End UnaryExpression"); } /* * Generate assembly code to define a variable's storage space. * @see cps450.oodle.analysis.DepthFirstAdapter#outAVarDeclaration(cps450.oodle.node.AVarDeclaration) */ @Override public void outAVarDeclaration(AVarDeclaration node) { //if (currentMethodDeclaration == null) { // emit(".comm _" + node.getName().getText() + ", 4, 4"); //} } }
true
true
public void outStart(Start node) { emit(""); emit(".text"); emit(".global main"); emit("main:"); // Instantiate globals emitClassInstantiationExpressionFor(classTable.get("Reader")); emit("popl _in"); emitClassInstantiationExpressionFor(classTable.get("Writer")); emit("popl _out"); // Instantiate the main class emitClassInstantiationExpressionFor(currentClassDeclaration); // Self argument is left on the stack from the instantiation expression emit("call " + getMethodLabel(currentClassName, "start")); emit("addl $4, %esp # Cleanup method argument"); // End the program emit("push $0"); emit("call exit"); emit(""); emit("# Global helpers"); emit(".text"); emit("__npe__:"); emit("pushl _out"); emitStringExpressionFor("\"The little gremlin running your program is scratching his head wondering how he is supposed to look up a method on a null object at line:\""); emit("call Writer_writeln"); //emit("addl $8, %esp"); emit("pushl _out"); emit("pushl errorLine"); emit("call Writer_writeint"); //emit("addl $8, %esp"); emit("pushl $1"); emit("call exit"); }
public void outStart(Start node) { emit(""); emit(".text"); emit(".global main"); emit("main:"); // Instantiate globals emitClassInstantiationExpressionFor(classTable.get("Reader")); emit("popl _in"); emitClassInstantiationExpressionFor(classTable.get("Writer")); emit("popl _out"); // Instantiate the main class emitClassInstantiationExpressionFor(currentClassDeclaration); // Self argument is left on the stack from the instantiation expression emit("call " + getMethodLabel(currentClassName, "start")); emit("addl $4, %esp # Cleanup method argument"); // End the program emit("push $0"); emit("call exit"); emit(""); emit("# Global helpers"); emit(".text"); emit("__npe__:"); emit("pushl _out"); emitStringExpressionFor("\"The little gremlin running your program is scratching his head wondering how he is supposed to look up a method on a null object at line: \""); emit("call Writer_write"); //emit("addl $8, %esp"); emit("pushl _out"); emit("pushl errorLine"); emit("call Writer_writeint"); //emit("addl $8, %esp"); emit("pushl $1"); emit("call exit"); }
diff --git a/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java b/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java index e26cb03f1..2ebdd98f0 100644 --- a/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java +++ b/freeplane/src/org/freeplane/features/common/attribute/AttributeBuilder.java @@ -1,233 +1,231 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Dimitry Polivaev * * This file author is Dimitry Polivaev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.common.attribute; import java.io.IOException; import org.freeplane.core.extension.IExtension; import org.freeplane.core.io.IAttributeHandler; import org.freeplane.core.io.IElementDOMHandler; import org.freeplane.core.io.IElementHandler; import org.freeplane.core.io.IExtensionElementWriter; import org.freeplane.core.io.ITreeWriter; import org.freeplane.core.io.ReadManager; import org.freeplane.core.io.WriteManager; import org.freeplane.features.common.map.MapModel; import org.freeplane.features.common.map.MapReader; import org.freeplane.features.common.map.NodeModel; import org.freeplane.n3.nanoxml.XMLElement; class AttributeBuilder implements IElementDOMHandler { static class AttributeProperties { String attributeName; String attributeValue; } static class RegisteredAttributeProperties { String attributeName; boolean manual = false; boolean restricted = false; boolean visible = false; } public static final String XML_NODE_ATTRIBUTE = "attribute"; public static final String XML_NODE_ATTRIBUTE_LAYOUT = "attribute_layout"; public static final String XML_NODE_ATTRIBUTE_REGISTRY = "attribute_registry"; public static final String XML_NODE_REGISTERED_ATTRIBUTE_NAME = "attribute_name"; public static final String XML_NODE_REGISTERED_ATTRIBUTE_VALUE = "attribute_value"; final private AttributeController attributeController; // // final private Controller controller; final private MapReader mapReader; public AttributeBuilder(final AttributeController attributeController, final MapReader mapReader) { this.attributeController = attributeController; this.mapReader = mapReader; } public Object createElement(final Object parent, final String tag, final XMLElement attributes) { if (tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE)) { return new AttributeProperties(); } if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME)) { return new RegisteredAttributeProperties(); } if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE) || tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY)) { return parent; } return null; } public void endElement(final Object parent, final String tag, final Object userObject, final XMLElement dom) { /* attributes */ if (tag.equals(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME)) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; if (rap.visible) { AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setVisibility(true); } if (rap.restricted) { AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setRestriction(true); } if (rap.manual) { AttributeRegistry.getRegistry(getMap()).getElement(rap.attributeName).setManual(true); } return; } if (parent instanceof NodeModel) { final NodeModel node = (NodeModel) parent; if (tag.equals(AttributeBuilder.XML_NODE_ATTRIBUTE)) { final AttributeProperties ap = (AttributeProperties) userObject; final Attribute attribute = new Attribute(ap.attributeName, ap.attributeValue); attributeController.createAttributeTableModel(node); final NodeAttributeTableModel model = NodeAttributeTableModel.getModel(node); model.addRowNoUndo(attribute); attributeController.setStateIcon(model); return; } return; } } private MapModel getMap() { return mapReader.getCurrentNodeTreeCreator().getCreatedMap(); } private void registerAttributeHandlers(final ReadManager reader) { reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.attributeName = value; AttributeRegistry.getRegistry(getMap()).registry(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.visible = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.restricted = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.manual = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; final Attribute attribute = new Attribute(rap.attributeName, value); final AttributeRegistry r = AttributeRegistry.getRegistry(getMap()); r.registry(attribute); } }); reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() { public Object createElement(final Object parent, final String tag, final XMLElement attributes) { return parent; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(0, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(1, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeName = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeValue = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { AttributeRegistry.getRegistry(getMap()).setRestricted(true); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { - ModelessAttributeController.getController().setAttributeViewType(getMap(), - value.toString()); final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap()); if(attributes != null) attributes.setAttributeViewType(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final int size = Integer.parseInt(value.toString()); AttributeRegistry.getRegistry(getMap()).setFontSize(size); } }); } /** */ public void registerBy(final ReadManager reader, final WriteManager writer) { reader.addElementHandler("attribute_registry", this); reader.addElementHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, this); reader.addElementHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, this); reader.addElementHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, this); writer.addExtensionElementWriter(NodeAttributeTableModel.class, new IExtensionElementWriter() { public void writeContent(final ITreeWriter writer, final Object node, final IExtension extension) throws IOException { final NodeAttributeTableModel attributes = (NodeAttributeTableModel) extension; attributes.save(writer); } }); writer.addExtensionElementWriter(AttributeRegistry.class, new IExtensionElementWriter() { public void writeContent(final ITreeWriter writer, final Object node, final IExtension extension) throws IOException { final AttributeRegistry attributes = (AttributeRegistry) extension; attributes.write(writer); } }); registerAttributeHandlers(reader); } public void setAttributes(final String tag, final Object node, final XMLElement attributes) { } }
true
true
private void registerAttributeHandlers(final ReadManager reader) { reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.attributeName = value; AttributeRegistry.getRegistry(getMap()).registry(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.visible = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.restricted = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.manual = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; final Attribute attribute = new Attribute(rap.attributeName, value); final AttributeRegistry r = AttributeRegistry.getRegistry(getMap()); r.registry(attribute); } }); reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() { public Object createElement(final Object parent, final String tag, final XMLElement attributes) { return parent; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(0, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(1, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeName = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeValue = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { AttributeRegistry.getRegistry(getMap()).setRestricted(true); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { ModelessAttributeController.getController().setAttributeViewType(getMap(), value.toString()); final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap()); if(attributes != null) attributes.setAttributeViewType(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final int size = Integer.parseInt(value.toString()); AttributeRegistry.getRegistry(getMap()).setFontSize(size); } }); }
private void registerAttributeHandlers(final ReadManager reader) { reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.attributeName = value; AttributeRegistry.getRegistry(getMap()).registry(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "VISIBLE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.visible = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.restricted = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_NAME, "MANUAL", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; rap.manual = true; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_REGISTERED_ATTRIBUTE_VALUE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final RegisteredAttributeProperties rap = (RegisteredAttributeProperties) userObject; final Attribute attribute = new Attribute(rap.attributeName, value); final AttributeRegistry r = AttributeRegistry.getRegistry(getMap()); r.registry(attribute); } }); reader.addElementHandler(XML_NODE_ATTRIBUTE_LAYOUT, new IElementHandler() { public Object createElement(final Object parent, final String tag, final XMLElement attributes) { return parent; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "NAME_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(0, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_LAYOUT, "VALUE_WIDTH", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final NodeModel node = (NodeModel) userObject; attributeController.createAttributeTableModel(node); final AttributeTableLayoutModel layout = NodeAttributeTableModel.getModel(node).getLayout(); layout.setColumnWidth(1, Integer.parseInt(value));; } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "NAME", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeName = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE, "VALUE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeProperties ap = (AttributeProperties) userObject; ap.attributeValue = value.toString(); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "RESTRICTED", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { AttributeRegistry.getRegistry(getMap()).setRestricted(true); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "SHOW_ATTRIBUTES", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final AttributeRegistry attributes = AttributeRegistry.getRegistry(getMap()); if(attributes != null) attributes.setAttributeViewType(value); } }); reader.addAttributeHandler(AttributeBuilder.XML_NODE_ATTRIBUTE_REGISTRY, "FONT_SIZE", new IAttributeHandler() { public void setAttribute(final Object userObject, final String value) { final int size = Integer.parseInt(value.toString()); AttributeRegistry.getRegistry(getMap()).setFontSize(size); } }); }
diff --git a/src/achievements/Actor.java b/src/achievements/Actor.java index 685bcb9..ac307c5 100644 --- a/src/achievements/Actor.java +++ b/src/achievements/Actor.java @@ -1,29 +1,29 @@ package achievements; import org.pircbotx.hooks.events.ActionEvent; import database.Database; public class Actor extends Achievement { public Actor(Database db) { super(db); } @Override protected int getAchievementId() { return 14; } public void onAction(ActionEvent event) { String nick = event.getUser().getNick(); db.increaseCount(nick, getAchievementId()); if(db.getCount(nick, getAchievementId()) >= 10) { if(!db.hasAchievement(nick, getAchievementId())) { db.giveAchievement(nick, getAchievementId()); - event.respond(getAwardString(nick)); + event.getBot().sendMessage("#tulpa", getAwardString(nick)); } } } }
true
true
public void onAction(ActionEvent event) { String nick = event.getUser().getNick(); db.increaseCount(nick, getAchievementId()); if(db.getCount(nick, getAchievementId()) >= 10) { if(!db.hasAchievement(nick, getAchievementId())) { db.giveAchievement(nick, getAchievementId()); event.respond(getAwardString(nick)); } } }
public void onAction(ActionEvent event) { String nick = event.getUser().getNick(); db.increaseCount(nick, getAchievementId()); if(db.getCount(nick, getAchievementId()) >= 10) { if(!db.hasAchievement(nick, getAchievementId())) { db.giveAchievement(nick, getAchievementId()); event.getBot().sendMessage("#tulpa", getAwardString(nick)); } } }
diff --git a/kernel/src/main/java/org/vosao/business/impl/imex/PageExporter.java b/kernel/src/main/java/org/vosao/business/impl/imex/PageExporter.java index 05313af..b579b76 100644 --- a/kernel/src/main/java/org/vosao/business/impl/imex/PageExporter.java +++ b/kernel/src/main/java/org/vosao/business/impl/imex/PageExporter.java @@ -1,356 +1,356 @@ /** * Vosao CMS. Simple CMS for Google App Engine. * Copyright (C) 2009 Vosao development team * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * email: [email protected] */ package org.vosao.business.impl.imex; import java.io.IOException; import java.text.ParseException; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.zip.ZipOutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Element; import org.vosao.business.Business; import org.vosao.business.decorators.TreeItemDecorator; import org.vosao.business.impl.imex.dao.DaoTaskAdapter; import org.vosao.dao.Dao; import org.vosao.dao.DaoTaskException; import org.vosao.entity.CommentEntity; import org.vosao.entity.ContentEntity; import org.vosao.entity.FolderEntity; import org.vosao.entity.LanguageEntity; import org.vosao.entity.PageEntity; import org.vosao.entity.StructureEntity; import org.vosao.entity.StructureTemplateEntity; import org.vosao.entity.TemplateEntity; import org.vosao.enums.PageState; import org.vosao.enums.PageType; import org.vosao.utils.DateUtil; import org.vosao.utils.StrUtil; import org.vosao.utils.XmlUtil; public class PageExporter extends AbstractExporter { private static final Log logger = LogFactory.getLog(PageExporter.class); private ResourceExporter resourceExporter; private ConfigExporter configExporter; private FormExporter formExporter; private UserExporter userExporter; private PagePermissionExporter pagePermissionExporter; public PageExporter(Dao aDao, Business aBusiness, DaoTaskAdapter daoTaskAdapter) { super(aDao, aBusiness, daoTaskAdapter); resourceExporter = new ResourceExporter(aDao, aBusiness, daoTaskAdapter); configExporter = new ConfigExporter(aDao, aBusiness, daoTaskAdapter); formExporter = new FormExporter(aDao, aBusiness, daoTaskAdapter); userExporter = new UserExporter(aDao, aBusiness, daoTaskAdapter); pagePermissionExporter = new PagePermissionExporter(aDao, aBusiness, daoTaskAdapter); } private void createPageXML(TreeItemDecorator<PageEntity> page, Element root) { Element pageElement = root.addElement("page"); createPageDetailsXML(page.getEntity(), pageElement); createPageVersionXML(page.getEntity(), pageElement); createCommentsXML(page, pageElement); for (TreeItemDecorator<PageEntity> child : page.getChildren()) { createPageXML(child, pageElement); } pagePermissionExporter.createPagePermissionsXML(pageElement, page.getEntity().getFriendlyURL()); } private void createPageVersionXML(PageEntity page, Element pageElement) { List<PageEntity> versions = getDao().getPageDao().selectByUrl( page.getFriendlyURL()); for (PageEntity pageVersion : versions) { if (!pageVersion.getId().equals(page.getId())) { createPageDetailsXML(pageVersion, pageElement.addElement( "page-version")); } } } private static String packTitle(PageEntity page) { StringBuffer b = new StringBuffer("<title>"); b.append(page.getTitleValue()).append("</title>"); return b.toString(); } private static String unpackTitle(String xml) { if (!xml.startsWith("<title>")) { return "en" + xml; } return xml.replace("<title>", "").replace("</title>", ""); } private void createPageDetailsXML(PageEntity page, Element pageElement) { pageElement.addAttribute("url", page.getFriendlyURL()); pageElement.addAttribute("title", packTitle(page)); pageElement.addAttribute("commentsEnabled", String.valueOf( page.isCommentsEnabled())); if (page.getPublishDate() != null) { pageElement.addAttribute("publishDate", DateUtil.toString(page.getPublishDate())); } TemplateEntity template = getDao().getTemplateDao().getById( page.getTemplate()); if (template != null) { pageElement.addAttribute("theme", template.getUrl()); } pageElement.addElement("version").setText(page.getVersion().toString()); pageElement.addElement("versionTitle").setText(page.getVersionTitle()); pageElement.addElement("state").setText(page.getState().name()); String createUserId = "1"; pageElement.addElement("createUserEmail").setText( page.getCreateUserEmail()); pageElement.addElement("modUserId").setText( page.getModUserEmail()); if (page.getCreateDate() != null) { pageElement.addElement("createDate").setText( DateUtil.dateTimeToString(page.getCreateDate())); } if (page.getModDate() != null) { pageElement.addElement("modDate").setText( DateUtil.dateTimeToString(page.getModDate())); } StructureEntity structure = getDao().getStructureDao().getById( page.getStructureId()); pageElement.addElement("structure").setText( structure == null ? "" : structure.getTitle()); StructureTemplateEntity structureTemplate = getDao() .getStructureTemplateDao().getById(page.getStructureTemplateId()); pageElement.addElement("structureTemplate").setText( structureTemplate == null ? "" : structureTemplate.getTitle()); pageElement.addElement("pageType").setText(page.getPageType().name()); List<ContentEntity> contents = getDao().getPageDao().getContents( page.getId()); for (ContentEntity content : contents) { Element contentElement = pageElement.addElement("content"); contentElement.addAttribute("language", content.getLanguageCode()); contentElement.addText(content.getContent()); } } private void createCommentsXML(TreeItemDecorator<PageEntity> page, Element pageElement) { Element commentsElement = pageElement.addElement("comments"); List<CommentEntity> comments = getDao().getCommentDao().getByPage( page.getEntity().getFriendlyURL()); for (CommentEntity comment : comments) { Element commentElement = commentsElement.addElement("comment"); commentElement.addAttribute("name", comment.getName()); commentElement.addAttribute("disabled", String.valueOf( comment.isDisabled())); commentElement.addAttribute("publishDate", DateUtil.dateTimeToString(comment.getPublishDate())); commentElement.setText(comment.getContent()); } } public void createPagesXML(Element siteElement) { Element pages = siteElement.addElement("pages"); TreeItemDecorator<PageEntity> pageRoot = getBusiness() .getPageBusiness().getTree(); createPageXML(pageRoot, pages); } public void addContentResources(final ZipOutputStream out) throws IOException { TreeItemDecorator<FolderEntity> root = getBusiness() .getFolderBusiness().getTree(); TreeItemDecorator<FolderEntity> folder = getBusiness() .getFolderBusiness().findFolderByPath(root, "/page"); if (folder == null) { return; } resourceExporter.addResourcesFromFolder(out, folder, "page/"); } public void readPages(Element pages) throws DaoTaskException { for (Iterator<Element> i = pages.elementIterator(); i.hasNext(); ) { Element pageElement = i.next(); readPage(pageElement, null); } } private void readPage(Element pageElement, PageEntity parentPage) throws DaoTaskException { PageEntity page = readPageVersion(pageElement); for (Iterator<Element> i = pageElement.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals("page")) { readPage(element, page); } if (element.getName().equals("comments")) { readComments(element, page); } if (element.getName().equals("page-version")) { readPageVersion(element); } if (element.getName().equals("permissions")) { pagePermissionExporter.readPagePermissions(element, page.getFriendlyURL()); } } } private PageEntity readPageVersion(Element pageElement) throws DaoTaskException { String title = unpackTitle(pageElement.attributeValue("title")); String url = pageElement.attributeValue("url"); String themeUrl = pageElement.attributeValue("theme"); String commentsEnabled = pageElement.attributeValue("commentsEnabled"); Date publishDate = new Date(); if (pageElement.attributeValue("publishDate") != null) { try { publishDate = DateUtil.toDate(pageElement .attributeValue("publishDate")); } catch (ParseException e) { logger.error("Wrong date format " + pageElement.attributeValue("publishDate") + " " + title); } } TemplateEntity template = getDao().getTemplateDao().getByUrl(themeUrl); String templateId = null; if (template != null) { templateId = template.getId(); } PageEntity newPage = new PageEntity(); newPage.setTitleValue(title); newPage.setFriendlyURL(url); newPage.setTemplate(templateId); newPage.setPublishDate(publishDate); if (commentsEnabled != null) { newPage.setCommentsEnabled(Boolean.valueOf(commentsEnabled)); } newPage.setState(PageState.APPROVED); for (Iterator<Element> i = pageElement.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals("version")) { newPage.setVersion(XmlUtil.readIntegerText(element, 1)); } if (element.getName().equals("versionTitle")) { newPage.setVersionTitle(element.getText()); } if (element.getName().equals("state")) { newPage.setState(PageState.valueOf(element.getText())); } if (element.getName().equals("createUserEmail")) { newPage.setCreateUserEmail(element.getText()); } if (element.getName().equals("modUserEmail")) { newPage.setModUserEmail(element.getText()); } if (element.getName().equals("pageType")) { newPage.setPageType(PageType.valueOf(element.getText())); } if (element.getName().equals("structure")) { - StructureEntity structure = getDao().getStructureDao().getById( + StructureEntity structure = getDao().getStructureDao().getByTitle( element.getText()); newPage.setStructureId(structure == null ? "" : structure.getId()); } if (element.getName().equals("structureTemplate")) { StructureTemplateEntity structureTemplate = getDao() - .getStructureTemplateDao().getById(element.getText()); + .getStructureTemplateDao().getByTitle(element.getText()); newPage.setStructureTemplateId(structureTemplate == null ? "" : structureTemplate.getId()); } if (element.getName().equals("createDate")) { try { newPage.setCreateDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } if (element.getName().equals("modDate")) { try { newPage.setModDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } } PageEntity page = getDao().getPageDao().getByUrlVersion(url, newPage.getVersion()); if (page != null) { page.copy(newPage); } else { page = newPage; } getDaoTaskAdapter().pageSave(page); readContents(pageElement, page); return page; } private void readContents(Element pageElement, PageEntity page) throws DaoTaskException { for (Iterator<Element> i = pageElement.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals("content")) { String content = element.getText(); String language = element.attributeValue("language"); if (language == null) { language = LanguageEntity.ENGLISH_CODE; } getDaoTaskAdapter().setPageContent(page.getId(), language, content); } } } private void readComments(Element commentsElement, PageEntity page) throws DaoTaskException { for (Iterator<Element> i = commentsElement.elementIterator(); i .hasNext();) { Element element = i.next(); if (element.getName().equals("comment")) { String name = element.attributeValue("name"); Date publishDate = new Date(); try { publishDate = DateUtil.dateTimeToDate(element .attributeValue("publishDate")); } catch (ParseException e) { logger.error("Error parsing comment publish date " + element.attributeValue("publishDate")); } boolean disabled = Boolean.valueOf(element .attributeValue("disabled")); String content = element.getText(); CommentEntity comment = new CommentEntity(name, content, publishDate, page.getId(), disabled); getDaoTaskAdapter().commentSave(comment); } } } }
false
true
private PageEntity readPageVersion(Element pageElement) throws DaoTaskException { String title = unpackTitle(pageElement.attributeValue("title")); String url = pageElement.attributeValue("url"); String themeUrl = pageElement.attributeValue("theme"); String commentsEnabled = pageElement.attributeValue("commentsEnabled"); Date publishDate = new Date(); if (pageElement.attributeValue("publishDate") != null) { try { publishDate = DateUtil.toDate(pageElement .attributeValue("publishDate")); } catch (ParseException e) { logger.error("Wrong date format " + pageElement.attributeValue("publishDate") + " " + title); } } TemplateEntity template = getDao().getTemplateDao().getByUrl(themeUrl); String templateId = null; if (template != null) { templateId = template.getId(); } PageEntity newPage = new PageEntity(); newPage.setTitleValue(title); newPage.setFriendlyURL(url); newPage.setTemplate(templateId); newPage.setPublishDate(publishDate); if (commentsEnabled != null) { newPage.setCommentsEnabled(Boolean.valueOf(commentsEnabled)); } newPage.setState(PageState.APPROVED); for (Iterator<Element> i = pageElement.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals("version")) { newPage.setVersion(XmlUtil.readIntegerText(element, 1)); } if (element.getName().equals("versionTitle")) { newPage.setVersionTitle(element.getText()); } if (element.getName().equals("state")) { newPage.setState(PageState.valueOf(element.getText())); } if (element.getName().equals("createUserEmail")) { newPage.setCreateUserEmail(element.getText()); } if (element.getName().equals("modUserEmail")) { newPage.setModUserEmail(element.getText()); } if (element.getName().equals("pageType")) { newPage.setPageType(PageType.valueOf(element.getText())); } if (element.getName().equals("structure")) { StructureEntity structure = getDao().getStructureDao().getById( element.getText()); newPage.setStructureId(structure == null ? "" : structure.getId()); } if (element.getName().equals("structureTemplate")) { StructureTemplateEntity structureTemplate = getDao() .getStructureTemplateDao().getById(element.getText()); newPage.setStructureTemplateId(structureTemplate == null ? "" : structureTemplate.getId()); } if (element.getName().equals("createDate")) { try { newPage.setCreateDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } if (element.getName().equals("modDate")) { try { newPage.setModDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } } PageEntity page = getDao().getPageDao().getByUrlVersion(url, newPage.getVersion()); if (page != null) { page.copy(newPage); } else { page = newPage; } getDaoTaskAdapter().pageSave(page); readContents(pageElement, page); return page; }
private PageEntity readPageVersion(Element pageElement) throws DaoTaskException { String title = unpackTitle(pageElement.attributeValue("title")); String url = pageElement.attributeValue("url"); String themeUrl = pageElement.attributeValue("theme"); String commentsEnabled = pageElement.attributeValue("commentsEnabled"); Date publishDate = new Date(); if (pageElement.attributeValue("publishDate") != null) { try { publishDate = DateUtil.toDate(pageElement .attributeValue("publishDate")); } catch (ParseException e) { logger.error("Wrong date format " + pageElement.attributeValue("publishDate") + " " + title); } } TemplateEntity template = getDao().getTemplateDao().getByUrl(themeUrl); String templateId = null; if (template != null) { templateId = template.getId(); } PageEntity newPage = new PageEntity(); newPage.setTitleValue(title); newPage.setFriendlyURL(url); newPage.setTemplate(templateId); newPage.setPublishDate(publishDate); if (commentsEnabled != null) { newPage.setCommentsEnabled(Boolean.valueOf(commentsEnabled)); } newPage.setState(PageState.APPROVED); for (Iterator<Element> i = pageElement.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals("version")) { newPage.setVersion(XmlUtil.readIntegerText(element, 1)); } if (element.getName().equals("versionTitle")) { newPage.setVersionTitle(element.getText()); } if (element.getName().equals("state")) { newPage.setState(PageState.valueOf(element.getText())); } if (element.getName().equals("createUserEmail")) { newPage.setCreateUserEmail(element.getText()); } if (element.getName().equals("modUserEmail")) { newPage.setModUserEmail(element.getText()); } if (element.getName().equals("pageType")) { newPage.setPageType(PageType.valueOf(element.getText())); } if (element.getName().equals("structure")) { StructureEntity structure = getDao().getStructureDao().getByTitle( element.getText()); newPage.setStructureId(structure == null ? "" : structure.getId()); } if (element.getName().equals("structureTemplate")) { StructureTemplateEntity structureTemplate = getDao() .getStructureTemplateDao().getByTitle(element.getText()); newPage.setStructureTemplateId(structureTemplate == null ? "" : structureTemplate.getId()); } if (element.getName().equals("createDate")) { try { newPage.setCreateDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } if (element.getName().equals("modDate")) { try { newPage.setModDate(DateUtil.dateTimeToDate( element.getText())); } catch (ParseException e) { logger.error("Wrong date format for createDate " + element.getText()); } } } PageEntity page = getDao().getPageDao().getByUrlVersion(url, newPage.getVersion()); if (page != null) { page.copy(newPage); } else { page = newPage; } getDaoTaskAdapter().pageSave(page); readContents(pageElement, page); return page; }
diff --git a/signserver/src/java/org/signserver/common/clusterclassloader/FindInterfacesClassLoader.java b/signserver/src/java/org/signserver/common/clusterclassloader/FindInterfacesClassLoader.java index 8572d7531..6335e07f3 100644 --- a/signserver/src/java/org/signserver/common/clusterclassloader/FindInterfacesClassLoader.java +++ b/signserver/src/java/org/signserver/common/clusterclassloader/FindInterfacesClassLoader.java @@ -1,127 +1,130 @@ /************************************************************************* * * * SignServer: The OpenSource Automated Signing Server * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.signserver.common.clusterclassloader; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.jar.JarInputStream; import org.apache.log4j.Logger; /** * Class loader used to find all classes that implements interfaces * of a collection of classes. * * Should only be used temporary when uploading a plug-in zip * to the ClusterClassLoader. * * @author Philip Vendil 15 maj 2008 * */ public class FindInterfacesClassLoader extends ClassLoader { public transient Logger log = Logger.getLogger(this.getClass()); /** * HashMap containing class name of class and the actual class. */ private HashMap<String, byte[]> availableClasses = new HashMap<String,byte[]>(); /** * HashMap containing loaded classes by class name and Class */ HashMap<String, Class<?>> loadedClasses = new HashMap<String,Class<?>>(); /** * Constructor generating all classes in the MARFileParser * So it is possible to search for implemented interfaces. * @param MARFileParser to use as repository. * @param part to generate classes for. * @throws IOException if something unexpected happened reading the Module Archive */ public FindInterfacesClassLoader(MARFileParser mARFileParser, String part) throws IOException{ Map<String, JarInputStream> jarFiles = mARFileParser.getJARFiles(part); for(String jarName : jarFiles.keySet()){ Map<String, byte[]> resources = mARFileParser.getJarContent(jarFiles.get(jarName)); for(String next : resources.keySet()){ if(next.endsWith(".class")){ availableClasses.put(ClusterClassLoaderUtils.getClassNameFromResourcePath(next), resources.get(next)); } } } } /** * Finds all implemented interfaces of the specified resource path. * @param resourcePath with '/' and '.class' * @return A List of implemented interfaces, an empty list if class couldn't be found or didn't implement any interfaces, never null */ public Collection<String> getImplementedInterfaces(String resourcePath){ Set<String> implInterfaces = new HashSet<String>(); Class<?> c = null; try { - c = findClass(ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath)); + String classNameFromResourcePath = ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath); + if(classNameFromResourcePath != null){ + c = findClass(classNameFromResourcePath); + } } catch (ClassNotFoundException e) { } if(c != null){ for(Class<?> inter : c.getInterfaces()){ implInterfaces.add(inter.getName()); } if(c.getSuperclass() != null && !c.getSuperclass().getName().equals(Object.class.getName())){ String superClassResourceName = ClusterClassLoaderUtils.getResourcePathFromClassName(c.getSuperclass().getName()); implInterfaces.addAll(getImplementedInterfaces(superClassResourceName)); } } return implInterfaces; } /* (non-Javadoc) * @see java.lang.ClassLoader#findClass(java.lang.String) */ @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classData = availableClasses.get(name); Class<?> retval = null; try{ retval = getParent().loadClass(name); }catch(ClassNotFoundException e){ if(loadedClasses.containsKey(name)){ retval = loadedClasses.get(name); }else{ System.out.println("name : " + name); retval = defineClass(name, classData, 0, classData.length); loadedClasses.put(name, retval); } } if(retval == null){ throw new ClassNotFoundException("Error class " + name + " not found."); } return retval; } }
true
true
public Collection<String> getImplementedInterfaces(String resourcePath){ Set<String> implInterfaces = new HashSet<String>(); Class<?> c = null; try { c = findClass(ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath)); } catch (ClassNotFoundException e) { } if(c != null){ for(Class<?> inter : c.getInterfaces()){ implInterfaces.add(inter.getName()); } if(c.getSuperclass() != null && !c.getSuperclass().getName().equals(Object.class.getName())){ String superClassResourceName = ClusterClassLoaderUtils.getResourcePathFromClassName(c.getSuperclass().getName()); implInterfaces.addAll(getImplementedInterfaces(superClassResourceName)); } } return implInterfaces; }
public Collection<String> getImplementedInterfaces(String resourcePath){ Set<String> implInterfaces = new HashSet<String>(); Class<?> c = null; try { String classNameFromResourcePath = ClusterClassLoaderUtils.getClassNameFromResourcePath(resourcePath); if(classNameFromResourcePath != null){ c = findClass(classNameFromResourcePath); } } catch (ClassNotFoundException e) { } if(c != null){ for(Class<?> inter : c.getInterfaces()){ implInterfaces.add(inter.getName()); } if(c.getSuperclass() != null && !c.getSuperclass().getName().equals(Object.class.getName())){ String superClassResourceName = ClusterClassLoaderUtils.getResourcePathFromClassName(c.getSuperclass().getName()); implInterfaces.addAll(getImplementedInterfaces(superClassResourceName)); } } return implInterfaces; }
diff --git a/simulator/PlantPresenter.java b/simulator/PlantPresenter.java index 7c51b52..0a600b0 100644 --- a/simulator/PlantPresenter.java +++ b/simulator/PlantPresenter.java @@ -1,83 +1,83 @@ package simulator; public class PlantPresenter { private Plant model; public PlantPresenter(Plant model) { this.model = model; } public void saveState(String filename){ // write serialised Plant to file? } public void loadState(String filename) { // read plant object from file } public void updatePlant() { for (int i = 0; i<model.plantComponents.size(); i++) { model.plantComponents.get(i).updateState(); } for (int z = 0; z<model.beingRepaired.size(); z++) { model.beingRepaired.get(i).decTimeStepsRemaning(); int temp = model.beingRepaired.get(i).getTimeStepsRemaining(); if(temp == 0) { //remove from beingRepaired and add to plantComponents } } // Go through all components and call updateState() // This will do things in Reactor and Condenser objects etc. } public void repairComponent(String name) { // name of component to be repaired List<PlantComponents> temp = model.getFailedComponents(); for(int i = 0; i<temp.size(); i++) { if(temp.getName().equals(name)) { model.beingRepaired.add(temp.get(i)); model.failedComponents.remove(model.failedComponents.get(i)); break; } } } public void checkFailures() { List<PlantComponent> temp; temp = new ArrayList<PlantComponent>(); for (int i = 0; i<model.plantComponents.size(); i++) { if(model.plantComponents.get(i).checkFailures() = true) temp.add(plantComponents.get(i)); } int NUMBER_FAILED = temp.size(); if(NUMBER_FAILED > 0 ) { Random random = new Random(); int selection = random.nextInt(NUMBER_FAILED); String failed = temp.get(selection).getName(); for (int x = 0; x<model.plantComponents.size(); x++) { if(model.plantComponents.get(x).getName.equals(failed)) { // code to specify element of <plantComponents>, toggle its operational state, remove it from <plantComponents> and add it to <failedComponents> model.plantComponents.get(x).setOperational(false); model.failedComponents.add(plantComponents.get(x)); - plantComponents.remove(plantComponents.get(x)); + model.plantComponents.remove(model.plantComponents.get(x)); break; } } } } public void togglePaused() { } public void calcSystemFlow() { // Complex shit! } }
true
true
public void checkFailures() { List<PlantComponent> temp; temp = new ArrayList<PlantComponent>(); for (int i = 0; i<model.plantComponents.size(); i++) { if(model.plantComponents.get(i).checkFailures() = true) temp.add(plantComponents.get(i)); } int NUMBER_FAILED = temp.size(); if(NUMBER_FAILED > 0 ) { Random random = new Random(); int selection = random.nextInt(NUMBER_FAILED); String failed = temp.get(selection).getName(); for (int x = 0; x<model.plantComponents.size(); x++) { if(model.plantComponents.get(x).getName.equals(failed)) { // code to specify element of <plantComponents>, toggle its operational state, remove it from <plantComponents> and add it to <failedComponents> model.plantComponents.get(x).setOperational(false); model.failedComponents.add(plantComponents.get(x)); plantComponents.remove(plantComponents.get(x)); break; } } } }
public void checkFailures() { List<PlantComponent> temp; temp = new ArrayList<PlantComponent>(); for (int i = 0; i<model.plantComponents.size(); i++) { if(model.plantComponents.get(i).checkFailures() = true) temp.add(plantComponents.get(i)); } int NUMBER_FAILED = temp.size(); if(NUMBER_FAILED > 0 ) { Random random = new Random(); int selection = random.nextInt(NUMBER_FAILED); String failed = temp.get(selection).getName(); for (int x = 0; x<model.plantComponents.size(); x++) { if(model.plantComponents.get(x).getName.equals(failed)) { // code to specify element of <plantComponents>, toggle its operational state, remove it from <plantComponents> and add it to <failedComponents> model.plantComponents.get(x).setOperational(false); model.failedComponents.add(plantComponents.get(x)); model.plantComponents.remove(model.plantComponents.get(x)); break; } } } }
diff --git a/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/view/TouchImageView.java b/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/view/TouchImageView.java index fb2f786..5de4cee 100644 --- a/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/view/TouchImageView.java +++ b/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/view/TouchImageView.java @@ -1,409 +1,410 @@ /** * TouchImageView.java * By: Michael Ortiz * Updated By: Patrick Lackemacher * Updated By: Babay88 * Updated By: Adam Rosenfield * ------------------- * Extends Android ImageView to include pinch zooming and panning. * * Source: https://github.com/MikeOrtiz/TouchImageView * * * Copyright (c) 2012 Michael Ortiz * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE */ package com.adamrosenfield.wordswithcrosses.view; import java.util.logging.Logger; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.widget.ImageView; public class TouchImageView extends ImageView { protected static Logger LOG = Logger.getLogger("com.adamrosenfield.wordswithcrosses"); private Matrix matrix; // We can be in one of these 3 states private enum Mode { NONE, DRAG, ZOOM } private Mode mode = Mode.NONE; // Remember some things for zooming private PointF last = new PointF(); private PointF start = new PointF(); private boolean canScale = true; private float scale = 1f; private float minScale = 1f; private float maxScale = 3f; private float[] m; private int viewWidth, viewHeight; private int clickSlop = 3; protected float origWidth, origHeight; private int oldMeasuredWidth, oldMeasuredHeight; private long lastClickTime = -1; private ScaleGestureDetectorProxy mScaleDetector; private boolean couldBeLongClick; private LongClickDetector lastLongClickDetector; public TouchImageView(Context context) { super(context); sharedConstructing(context); } public TouchImageView(Context context, AttributeSet attrs) { super(context, attrs); sharedConstructing(context); } private void sharedConstructing(Context context) { super.setClickable(true); mScaleDetector = ScaleGestureDetectorProxy.create(context, this); matrix = new Matrix(); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); start.set(last); mode = Mode.DRAG; endLongClickDetection(); couldBeLongClick = true; lastLongClickDetector = new LongClickDetector(); postDelayed(lastLongClickDetector, ViewConfiguration.getLongPressTimeout()); break; case MotionEvent.ACTION_MOVE: if (mode == Mode.DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; if (couldBeLongClick && ((int)Math.abs(curr.x - last.x) > clickSlop || (int)Math.abs(curr.y - last.y) > clickSlop)) { endLongClickDetection(); } if (!couldBeLongClick) { last.set(curr.x, curr.y); translate(deltaX, deltaY); } } break; case MotionEvent.ACTION_UP: if (mode != Mode.DRAG) { mode = Mode.NONE; break; } mode = Mode.NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff <= clickSlop && yDiff <= clickSlop) { long now = System.currentTimeMillis(); if (now - lastClickTime < ViewConfiguration.getDoubleTapTimeout()) { onDoubleClick(pixelToBitmapPos(curr.x, curr.y)); } else { onClick(pixelToBitmapPos(curr.x, curr.y)); } lastClickTime = now; } endLongClickDetection(); break; case MotionEvent.ACTION_POINTER_UP: mode = Mode.NONE; + endLongClickDetection(); break; } return true; // indicate event was handled } }); } private void endLongClickDetection() { if (couldBeLongClick) { couldBeLongClick = false; lastLongClickDetector.disable(); lastLongClickDetector = null; } } // Click callbacks, which can be overridden by subclasses. By default, // they just generate regular click events, which can be received through // normal OnClickListener instances (but without the position information). protected void onClick(PointF pos) { performClick(); } protected void onDoubleClick(PointF pos) { performClick(); } protected void onLongClick(PointF pos) { performLongClick(); } public void translate(float dx, float dy) { float fixTransX = getFixDragTrans(dx, viewWidth, origWidth * scale); float fixTransY = getFixDragTrans(dy, viewHeight, origHeight * scale); matrix.postTranslate(fixTransX, fixTransY); onMatrixChanged(); } public void setTranslate(float x, float y) { setScaleAndTranslate(scale, x, y); } public void setCanScale(boolean canScale) { this.canScale = canScale; } public void setMinScale(float minScale) { this.minScale = minScale; } public void setMaxScale(float maxScale) { this.maxScale = maxScale; } public void setClickSlop(int clickSlop) { this.clickSlop = clickSlop; } public void setScaleAndTranslate(float newScale, float tx, float ty) { scale = newScale; matrix.setScale(newScale, newScale); matrix.postTranslate(tx, ty); onMatrixChanged(); } protected void onScaleEnd(float scale) { // No-op by default, can be overridden by subclasses } @TargetApi(8) public class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener { public boolean onScaleBegin(ScaleGestureDetector detector) { if (!canScale) { return false; } mode = Mode.ZOOM; endLongClickDetection(); return true; } public boolean onScale(ScaleGestureDetector detector) { float scaleFactor = detector.getScaleFactor(); float origScale = scale; scale *= scaleFactor; if (scale > maxScale) { scale = maxScale; scaleFactor = maxScale / origScale; } else if (scale < minScale) { scale = minScale; scaleFactor = minScale / origScale; } if (origWidth * scale <= viewWidth || origHeight * scale <= viewHeight) { matrix.postScale(scaleFactor, scaleFactor, viewWidth / 2.0f, viewHeight / 2.0f); } else { matrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY()); } onMatrixChanged(); return true; } public void onScaleEnd(ScaleGestureDetector detector) { TouchImageView.this.onScaleEnd(scale); } } private void onMatrixChanged() { fixTrans(); setImageMatrix(matrix); invalidate(); } private void fixTrans() { matrix.getValues(m); float transX = m[Matrix.MTRANS_X]; float transY = m[Matrix.MTRANS_Y]; float fixTransX = getFixTrans(transX, viewWidth, origWidth * scale); float fixTransY = getFixTrans(transY, viewHeight, origHeight * scale); if (fixTransX != 0 || fixTransY != 0) { matrix.postTranslate(fixTransX, fixTransY); } } private float getFixTrans(float trans, float viewSize, float contentSize) { float minTrans, maxTrans; if (contentSize <= viewSize) { minTrans = 0; maxTrans = viewSize - contentSize; } else { minTrans = viewSize - contentSize; maxTrans = 0; } if (trans < minTrans) { return -trans + minTrans; } if (trans > maxTrans) { return -trans + maxTrans; } return 0; } private float getFixDragTrans(float delta, float viewSize, float contentSize) { if (contentSize <= viewSize) { return 0; } return delta; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); viewWidth = MeasureSpec.getSize(widthMeasureSpec); viewHeight = MeasureSpec.getSize(heightMeasureSpec); if (oldMeasuredWidth == viewWidth && oldMeasuredHeight == viewHeight || viewWidth == 0 || viewHeight == 0) { return; } oldMeasuredHeight = viewHeight; oldMeasuredWidth = viewWidth; // Re-centers the image on device rotation //centerImage(); } public void centerImage() { // Fit to screen. Drawable drawable = getDrawable(); if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) return; int bmWidth = drawable.getIntrinsicWidth(); int bmHeight = drawable.getIntrinsicHeight(); //Log.d("bmSize", "bmWidth: " + bmWidth + " bmHeight : " + bmHeight); float scaleX = (float)viewWidth / (float)bmWidth; float scaleY = (float)viewHeight / (float)bmHeight; scale = Math.min(scaleX, scaleY); matrix.setScale(scale, scale); // Center the image float redundantXSpace = ((float)viewWidth - (scale * (float)bmWidth)) * 0.5f; float redundantYSpace = ((float)viewHeight - (scale * (float)bmHeight)) * 0.5f; matrix.postTranslate(redundantXSpace, redundantYSpace); origWidth = bmWidth; origHeight = bmHeight; setImageMatrix(matrix); fixTrans(); } public PointF pixelToBitmapPos(float x, float y) { Matrix invMatrix = new Matrix(); if (matrix.invert(invMatrix)) { float[] p = new float[]{x, y}; invMatrix.mapPoints(p); return new PointF(p[0], p[1]); } else { // Should not happen LOG.warning("pixelToBitmapPos: Failed to invert matrix!"); return new PointF(0.0f, 0.0f); } } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); origWidth = drawable.getIntrinsicWidth(); origHeight = drawable.getIntrinsicHeight(); } private class LongClickDetector implements Runnable { private boolean enabled = true; public void disable() { enabled = false; } public void run() { if (enabled) { mode = Mode.NONE; onLongClick(pixelToBitmapPos(last.x, last.y)); } } } }
true
true
private void sharedConstructing(Context context) { super.setClickable(true); mScaleDetector = ScaleGestureDetectorProxy.create(context, this); matrix = new Matrix(); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); start.set(last); mode = Mode.DRAG; endLongClickDetection(); couldBeLongClick = true; lastLongClickDetector = new LongClickDetector(); postDelayed(lastLongClickDetector, ViewConfiguration.getLongPressTimeout()); break; case MotionEvent.ACTION_MOVE: if (mode == Mode.DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; if (couldBeLongClick && ((int)Math.abs(curr.x - last.x) > clickSlop || (int)Math.abs(curr.y - last.y) > clickSlop)) { endLongClickDetection(); } if (!couldBeLongClick) { last.set(curr.x, curr.y); translate(deltaX, deltaY); } } break; case MotionEvent.ACTION_UP: if (mode != Mode.DRAG) { mode = Mode.NONE; break; } mode = Mode.NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff <= clickSlop && yDiff <= clickSlop) { long now = System.currentTimeMillis(); if (now - lastClickTime < ViewConfiguration.getDoubleTapTimeout()) { onDoubleClick(pixelToBitmapPos(curr.x, curr.y)); } else { onClick(pixelToBitmapPos(curr.x, curr.y)); } lastClickTime = now; } endLongClickDetection(); break; case MotionEvent.ACTION_POINTER_UP: mode = Mode.NONE; break; } return true; // indicate event was handled } }); }
private void sharedConstructing(Context context) { super.setClickable(true); mScaleDetector = ScaleGestureDetectorProxy.create(context, this); matrix = new Matrix(); m = new float[9]; setImageMatrix(matrix); setScaleType(ScaleType.MATRIX); setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { mScaleDetector.onTouchEvent(event); PointF curr = new PointF(event.getX(), event.getY()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: last.set(curr); start.set(last); mode = Mode.DRAG; endLongClickDetection(); couldBeLongClick = true; lastLongClickDetector = new LongClickDetector(); postDelayed(lastLongClickDetector, ViewConfiguration.getLongPressTimeout()); break; case MotionEvent.ACTION_MOVE: if (mode == Mode.DRAG) { float deltaX = curr.x - last.x; float deltaY = curr.y - last.y; if (couldBeLongClick && ((int)Math.abs(curr.x - last.x) > clickSlop || (int)Math.abs(curr.y - last.y) > clickSlop)) { endLongClickDetection(); } if (!couldBeLongClick) { last.set(curr.x, curr.y); translate(deltaX, deltaY); } } break; case MotionEvent.ACTION_UP: if (mode != Mode.DRAG) { mode = Mode.NONE; break; } mode = Mode.NONE; int xDiff = (int) Math.abs(curr.x - start.x); int yDiff = (int) Math.abs(curr.y - start.y); if (xDiff <= clickSlop && yDiff <= clickSlop) { long now = System.currentTimeMillis(); if (now - lastClickTime < ViewConfiguration.getDoubleTapTimeout()) { onDoubleClick(pixelToBitmapPos(curr.x, curr.y)); } else { onClick(pixelToBitmapPos(curr.x, curr.y)); } lastClickTime = now; } endLongClickDetection(); break; case MotionEvent.ACTION_POINTER_UP: mode = Mode.NONE; endLongClickDetection(); break; } return true; // indicate event was handled } }); }
diff --git a/src/main/java/escada/tpc/common/PerformanceCounters.java b/src/main/java/escada/tpc/common/PerformanceCounters.java index da90b67..aa536d7 100644 --- a/src/main/java/escada/tpc/common/PerformanceCounters.java +++ b/src/main/java/escada/tpc/common/PerformanceCounters.java @@ -1,139 +1,141 @@ package escada.tpc.common; public class PerformanceCounters implements PerformanceCountersMBean { private long performanceRefreshInterval = DEFAULT_REFRESH_INTERVAL; private float inCommingRate = 0F; private float commitRate = 0F; private float abortRate = 0F; private double latencyRate=0F; private int inCommingCounter = 0; private int abortCounter = 0; private int commitCounter = 0; private long lastComputationInComming, lastComputationAbort, lastComputationCommit = 0, lastComputationLatency=0; private double latencyAccumulator = 0; private PerformanceCounters() { } public synchronized float getAbortRate() { long current = System.currentTimeMillis(); long diff = current - lastComputationAbort; float t = abortRate; if (diff > performanceRefreshInterval && diff > 0) { t = ((float) abortCounter / (float) (diff)) * 1000; t = (t < MINIMUM_VALUE ? 0 : t); lastComputationAbort = current; abortCounter = 0; } abortRate = t; return (abortRate); } public synchronized float getCommitRate() { long current = System.currentTimeMillis(); long diff = current - lastComputationCommit; float t = commitRate; if (diff > performanceRefreshInterval && diff > 0) { t = ((float) commitCounter / (float) (diff)) * 1000; t = (t < MINIMUM_VALUE ? 0 : t); lastComputationCommit = current; commitCounter = 0; } commitRate = t; return (commitRate); } public synchronized float getIncommingRate() { long current = System.currentTimeMillis(); long diff = current - lastComputationInComming; float t = inCommingRate; if (diff > performanceRefreshInterval && diff > 0) { t = ((float) inCommingCounter / (float) (diff)) * 1000; t = (t < MINIMUM_VALUE ? 0 : t); lastComputationInComming = current; inCommingCounter = 0; } inCommingRate = t; return (inCommingRate); } public synchronized double getAverageLatency() { long current = System.currentTimeMillis(); long diff = current - lastComputationLatency; double t = this.latencyRate; if (diff > performanceRefreshInterval && diff > 0) { if(this.latencyCounter > 0) { t = ((double)this.latencyAccumulator) / ((double)this.latencyCounter); t = (t < MINIMUM_VALUE ? 0 : t); + } else { + t = 0.0; } this.lastComputationLatency = current; this.latencyCounter = 0; this.latencyAccumulator = 0; } latencyRate = t; return this.latencyRate; } public static synchronized void setIncommingRate() { if (reference != null) { reference.inCommingCounter++; } } public static synchronized void setAbortRate() { if (reference != null) { reference.abortCounter++; } } public static synchronized void setCommitRate() { if (reference != null) { reference.commitCounter++; } } public static PerformanceCounters getReference() { if (reference == null) { reference = new PerformanceCounters(); } return (reference); } private double latencyCounter = 0; public static synchronized void setLatency(double latency) { if (reference != null) { reference.latencyAccumulator += latency; reference.latencyCounter++; } } private static PerformanceCounters reference; public long getPerformanceRefreshInterval() { return this.performanceRefreshInterval; } public void setPerformanceRefreshInterval(long refreshInterval) { this.performanceRefreshInterval = refreshInterval; } }
true
true
public synchronized double getAverageLatency() { long current = System.currentTimeMillis(); long diff = current - lastComputationLatency; double t = this.latencyRate; if (diff > performanceRefreshInterval && diff > 0) { if(this.latencyCounter > 0) { t = ((double)this.latencyAccumulator) / ((double)this.latencyCounter); t = (t < MINIMUM_VALUE ? 0 : t); } this.lastComputationLatency = current; this.latencyCounter = 0; this.latencyAccumulator = 0; } latencyRate = t; return this.latencyRate; }
public synchronized double getAverageLatency() { long current = System.currentTimeMillis(); long diff = current - lastComputationLatency; double t = this.latencyRate; if (diff > performanceRefreshInterval && diff > 0) { if(this.latencyCounter > 0) { t = ((double)this.latencyAccumulator) / ((double)this.latencyCounter); t = (t < MINIMUM_VALUE ? 0 : t); } else { t = 0.0; } this.lastComputationLatency = current; this.latencyCounter = 0; this.latencyAccumulator = 0; } latencyRate = t; return this.latencyRate; }
diff --git a/Pigeon/trunk/src/pigeon/report/Utilities.java b/Pigeon/trunk/src/pigeon/report/Utilities.java index 376b48a..3d6d964 100644 --- a/Pigeon/trunk/src/pigeon/report/Utilities.java +++ b/Pigeon/trunk/src/pigeon/report/Utilities.java @@ -1,164 +1,164 @@ /* Copyright (C) 2005, 2006, 2007 Paul Richards. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pigeon.report; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.TreeSet; import pigeon.model.Clock; import pigeon.model.Constants; import pigeon.model.Distance; import pigeon.model.Member; import pigeon.model.Organization; import pigeon.model.Race; import pigeon.model.Time; /** Shared HTML bits. */ public final class Utilities { // Non-Creatable private Utilities() { } public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\" media=\"screen\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:8pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); - out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); + out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; text-align: left; }\n"); out.print(" </style>\n"); out.print(" <style type=\"text/css\" media=\"print\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:6pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; } public static void writeHtmlFooter(PrintStream out) throws IOException { out.print("</body>\n"); out.print("</html>\n"); out.flush(); if (out.checkError()) { throw new IOException(); } } /** Returns a list of all the different sections, or an empty collection if no section information is available. */ public static List<String> participatingSections(Organization club) { Set<String> result = new TreeSet<String>(); for (Member member: club.getMembers()) { String section = member.getSection(); if (section != null) { result.add(section); } } return new ArrayList<String>(result); } public static String stringPrintf(String format, Object... args) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.printf(format, args); writer.flush(); return buffer.toString(); } public static BirdResult calculateVelocity(Organization club, Race race, Clock clock, Time time) { Date correctedClockTime = clock.convertMemberTimeToMasterTime(new Date(time.getMemberTime()), race); int nightsSpentSleeping = (int)(time.getMemberTime() / Constants.MILLISECONDS_PER_DAY); long timeSpentSleeping = nightsSpentSleeping * race.getLengthOfDarknessEachNight(); double flyTimeInSeconds = (correctedClockTime.getTime() - race.getLiberationDate().getTime() - timeSpentSleeping) / 1000.0; Distance distance = club.getDistanceEntry(clock.getMember(), race.getRacepoint()).getDistance(); double velocityInMetresPerSecond = distance.getMetres() / flyTimeInSeconds; return new BirdResult(velocityInMetresPerSecond, time, correctedClockTime, distance); } /** Takes a multi-line string and makes it ready for HTML output by inserting the required "br" tags. */ public static String insertBrTags(final String lines) { try { BufferedReader reader = new BufferedReader(new StringReader(lines)); StringBuffer result = new StringBuffer(); boolean firstLine = true; String line; while ((line = reader.readLine()) != null) { if (!firstLine) { result.append("<br/>"); } result.append(line); firstLine = false; } return result.toString(); } catch (IOException e) { throw new IllegalArgumentException("Not expecting any IOExceptions"); } } }
true
true
public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\" media=\"screen\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:8pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print(" <style type=\"text/css\" media=\"print\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:6pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; }
public static PrintStream writeHtmlHeader(OutputStream stream, String title) throws IOException { PrintStream out = new PrintStream(stream, false, "UTF-8"); out.print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); out.print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"); out.print("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); out.print("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); out.print("<head>\n"); out.print(" <title>" + title + "</title>\n"); out.print(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"); out.print(" <style type=\"text/css\" media=\"screen\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:8pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; text-align: left; }\n"); out.print(" </style>\n"); out.print(" <style type=\"text/css\" media=\"print\">\n"); out.print(" body { font-family: Verdana, sans-serif; white-space: nowrap; }\n"); out.print(" .outer { text-align:center; page-break-after: always; }\n"); out.print(" .outer.last { page-break-after: auto; }\n"); out.print(" h1 { margin-bottom:10px; font-size:18pt; }\n"); out.print(" h2 { font-size:16pt; }\n"); out.print(" h3 { font-size:14pt; }\n"); out.print(" h2, h3 { margin-top:0; margin-bottom:5px; }\n"); out.print(" table { width:95%; border:1px solid #000000; border-collapse:collapse; font-size:6pt; margin-top:20px; }\n"); out.print(" th { border-bottom:3px solid #000000; text-align: left; }\n"); out.print(" td { border-bottom:1px solid #000000; page-break-inside:avoid; padding:3px 0 3px 0; }\n"); out.print(" </style>\n"); out.print("</head>\n"); out.print("<body>\n"); if (out.checkError()) { throw new IOException(); } return out; }
diff --git a/my-gdx-game/src/com/me/mygdxgame/Runner.java b/my-gdx-game/src/com/me/mygdxgame/Runner.java index ffba0f1..b8af27e 100644 --- a/my-gdx-game/src/com/me/mygdxgame/Runner.java +++ b/my-gdx-game/src/com/me/mygdxgame/Runner.java @@ -1,187 +1,188 @@ package com.me.mygdxgame; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.TimeUtils; public class Runner { private static final float JUMP_HEIGHT = 5; private Texture currentSprite; private Texture runningSprite[]; private Texture jumpingSprite[]; private Texture duckingSprite[]; private int animationIndex; private float lastFrameTime; protected Rectangle hitbox; private float RESW; private float RESH; final int SPRITE_WIDTH = 43; final int SPRITE_HEIGHT = 60; final int SCALE = 1; // Only affects hit box at the moment final int WIDTH = SPRITE_WIDTH * SCALE; final int HEIGHT = SPRITE_HEIGHT * SCALE; private OrthographicCamera camera; private float floorHeight; private int posX = -300; private float speedY; private final float gravity = -1; private float jumpSpeed; protected boolean released; enum State { jumping, running, dead, ducking }; State state; // Debug Runner(OrthographicCamera pcamera, float pheight) { RESW = pcamera.viewportHeight; RESH = pcamera.viewportHeight; camera = pcamera; floorHeight = pheight; create(); } public void create() { speedY = 0; Texture walkingInit[] = { new Texture(Gdx.files.internal("data/bearsum/walk1.png")), new Texture(Gdx.files.internal("data/bearsum/walk2.png")), new Texture(Gdx.files.internal("data/bearsum/walk3.png")), new Texture(Gdx.files.internal("data/bearsum/walk4.png")), new Texture(Gdx.files.internal("data/bearsum/walk3.png")), new Texture(Gdx.files.internal("data/bearsum/walk2.png"))}; runningSprite = walkingInit; Texture jumpingInit[] = { new Texture(Gdx.files.internal("data/bearsum/jump1.png")), new Texture(Gdx.files.internal("data/bearsum/jump2.png")), new Texture(Gdx.files.internal("data/bearsum/jump3.png")) }; jumpingSprite = jumpingInit; Texture duckingInit[] = { new Texture(Gdx.files.internal("data/bearsum/roll1.png")), new Texture(Gdx.files.internal("data/bearsum/roll2.png")), new Texture(Gdx.files.internal("data/bearsum/roll3.png")), new Texture(Gdx.files.internal("data/bearsum/roll4.png")), new Texture(Gdx.files.internal("data/bearsum/roll5.png")) }; duckingSprite = duckingInit; hitbox = new Rectangle(camera.position.x + posX, floorHeight, SPRITE_WIDTH, SPRITE_HEIGHT); animationIndex = 0; lastFrameTime = TimeUtils.nanoTime(); state = State.running; } public void draw(SpriteBatch batch) { switch (state) { case running: if (animationIndex > runningSprite.length - 1) { animationIndex = 0; } currentSprite = runningSprite[animationIndex]; break; case jumping: if (animationIndex > jumpingSprite.length - 1) { animationIndex = 0; } currentSprite = jumpingSprite[animationIndex]; break; case ducking: if (animationIndex > duckingSprite.length - 1) { animationIndex = 0; } + currentSprite = duckingSprite[animationIndex]; case dead: break; default: break; } batch.draw(currentSprite, hitbox.x, hitbox.y); if (TimeUtils.nanoTime() - lastFrameTime >= 100000000) { if (state == State.jumping) { if (animationIndex < jumpingSprite.length - 1) { animationIndex++; } } else { animationIndex++; } lastFrameTime = TimeUtils.nanoTime(); } } public void floorCheck() { if (speedY > 0) { state = state.jumping; jumpSpeed *= 0.70; } else { if (hitbox.y <= floorHeight) { if (state != State.ducking) { state = state.running; } jumpSpeed = JUMP_HEIGHT; hitbox.y = floorHeight; speedY = 0; } } } public void dispose() { currentSprite.dispose(); for (int i = 0; i < runningSprite.length; i++) { runningSprite[i].dispose(); } for (int i = 0; i < jumpingSprite.length; i++) { jumpingSprite[i].dispose(); } } public void update() { speedY += gravity; hitbox.y += speedY; hitbox.x = camera.position.x + posX; floorCheck(); } public void jump() { if (state == State.running && released == true) { speedY += jumpSpeed; } if (state == State.jumping && released == false) { speedY += jumpSpeed; } released = false; } public void release() { if (state == State.running) { released = true; } if (state == State.ducking) { hitbox.setHeight(SPRITE_HEIGHT); hitbox.setWidth(SPRITE_WIDTH); state = State.running; } } public void duck() { hitbox.setHeight(SPRITE_WIDTH); hitbox.setHeight(SPRITE_HEIGHT); if (state == State.running) { state = State.ducking; } } }
true
true
public void draw(SpriteBatch batch) { switch (state) { case running: if (animationIndex > runningSprite.length - 1) { animationIndex = 0; } currentSprite = runningSprite[animationIndex]; break; case jumping: if (animationIndex > jumpingSprite.length - 1) { animationIndex = 0; } currentSprite = jumpingSprite[animationIndex]; break; case ducking: if (animationIndex > duckingSprite.length - 1) { animationIndex = 0; } case dead: break; default: break; } batch.draw(currentSprite, hitbox.x, hitbox.y); if (TimeUtils.nanoTime() - lastFrameTime >= 100000000) { if (state == State.jumping) { if (animationIndex < jumpingSprite.length - 1) { animationIndex++; } } else { animationIndex++; } lastFrameTime = TimeUtils.nanoTime(); } }
public void draw(SpriteBatch batch) { switch (state) { case running: if (animationIndex > runningSprite.length - 1) { animationIndex = 0; } currentSprite = runningSprite[animationIndex]; break; case jumping: if (animationIndex > jumpingSprite.length - 1) { animationIndex = 0; } currentSprite = jumpingSprite[animationIndex]; break; case ducking: if (animationIndex > duckingSprite.length - 1) { animationIndex = 0; } currentSprite = duckingSprite[animationIndex]; case dead: break; default: break; } batch.draw(currentSprite, hitbox.x, hitbox.y); if (TimeUtils.nanoTime() - lastFrameTime >= 100000000) { if (state == State.jumping) { if (animationIndex < jumpingSprite.length - 1) { animationIndex++; } } else { animationIndex++; } lastFrameTime = TimeUtils.nanoTime(); } }
diff --git a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/examples/CollocationWriterExample.java b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/examples/CollocationWriterExample.java index 9e15fc0..692c234 100644 --- a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/examples/CollocationWriterExample.java +++ b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/examples/CollocationWriterExample.java @@ -1,69 +1,69 @@ /* * Copyright (C) 2012 Fabian Hirschmann <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.github.fhirschmann.clozegen.lib.examples; import com.github.fhirschmann.clozegen.lib.components.CollocationWriter; import com.github.fhirschmann.clozegen.lib.constraints.resources.PrepositionConstraintResource; import com.github.fhirschmann.clozegen.lib.pipeline.Pipeline; import de.tudarmstadt.ukp.dkpro.core.api.resources.DKProContext; import de.tudarmstadt.ukp.dkpro.core.io.imscwb.ImsCwbReader; import de.tudarmstadt.ukp.dkpro.teaching.corpus.BrownCorpusReader; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.collection.CollectionReader; import org.uimafit.factory.CollectionReaderFactory; import static org.uimafit.factory.AnalysisEngineFactory.createPrimitiveDescription; import static org.uimafit.factory.ExternalResourceFactory.createExternalResourceDescription; /** * This example demonstrates the usage of {@link CollocationWriterExample}. * * <p> * The brown_tei corpus is expected in $DKPRO_HOME. * </p> * * @author Fabian Hirschmann <[email protected]> */ public class CollocationWriterExample { public static void main(String[] args) throws Exception { Pipeline pipeline = new Pipeline(); CollectionReader cr = CollectionReaderFactory.createCollectionReader( BrownCorpusReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("brown_tei").getAbsolutePath(), BrownCorpusReader.PARAM_PATTERNS, new String[] {"[+]*.xml"}); CollectionReader wacky = CollectionReaderFactory.createCollectionReader( ImsCwbReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("wacky/uk/x").getAbsolutePath(), ImsCwbReader.PARAM_TAGGER_TAGSET, "en", ImsCwbReader.PARAM_PATTERNS, new String[] {"[+]*.xml.gz"}); AnalysisEngineDescription trigrams = createPrimitiveDescription( CollocationWriter.class, CollocationWriter.CONSTRAINT_KEY, createExternalResourceDescription(PrepositionConstraintResource.class), CollocationWriter.PARAM_OUTPUT_PATH, "target/test.txt"); pipeline.addStep(trigrams); - pipeline.run(wacky); + pipeline.run(cr); } }
true
true
public static void main(String[] args) throws Exception { Pipeline pipeline = new Pipeline(); CollectionReader cr = CollectionReaderFactory.createCollectionReader( BrownCorpusReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("brown_tei").getAbsolutePath(), BrownCorpusReader.PARAM_PATTERNS, new String[] {"[+]*.xml"}); CollectionReader wacky = CollectionReaderFactory.createCollectionReader( ImsCwbReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("wacky/uk/x").getAbsolutePath(), ImsCwbReader.PARAM_TAGGER_TAGSET, "en", ImsCwbReader.PARAM_PATTERNS, new String[] {"[+]*.xml.gz"}); AnalysisEngineDescription trigrams = createPrimitiveDescription( CollocationWriter.class, CollocationWriter.CONSTRAINT_KEY, createExternalResourceDescription(PrepositionConstraintResource.class), CollocationWriter.PARAM_OUTPUT_PATH, "target/test.txt"); pipeline.addStep(trigrams); pipeline.run(wacky); }
public static void main(String[] args) throws Exception { Pipeline pipeline = new Pipeline(); CollectionReader cr = CollectionReaderFactory.createCollectionReader( BrownCorpusReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("brown_tei").getAbsolutePath(), BrownCorpusReader.PARAM_PATTERNS, new String[] {"[+]*.xml"}); CollectionReader wacky = CollectionReaderFactory.createCollectionReader( ImsCwbReader.class, BrownCorpusReader.PARAM_PATH, DKProContext.getContext().getWorkspace("wacky/uk/x").getAbsolutePath(), ImsCwbReader.PARAM_TAGGER_TAGSET, "en", ImsCwbReader.PARAM_PATTERNS, new String[] {"[+]*.xml.gz"}); AnalysisEngineDescription trigrams = createPrimitiveDescription( CollocationWriter.class, CollocationWriter.CONSTRAINT_KEY, createExternalResourceDescription(PrepositionConstraintResource.class), CollocationWriter.PARAM_OUTPUT_PATH, "target/test.txt"); pipeline.addStep(trigrams); pipeline.run(cr); }
diff --git a/client/src/main/java/com/google/gwt/sample/contacts/client/Contacts.java b/client/src/main/java/com/google/gwt/sample/contacts/client/Contacts.java index 5485e80..54b4bb4 100644 --- a/client/src/main/java/com/google/gwt/sample/contacts/client/Contacts.java +++ b/client/src/main/java/com/google/gwt/sample/contacts/client/Contacts.java @@ -1,67 +1,67 @@ package com.google.gwt.sample.contacts.client; import com.google.gwt.core.client.GWT; import com.google.gwt.sample.contacts.client.gin.ContactGinjector; import com.google.gwt.sample.contacts.client.gin.ContactsServicesGinModule; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.RpcTokenException; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.rpc.XsrfToken; import com.google.gwt.user.client.rpc.XsrfTokenService; import com.google.gwt.user.client.rpc.XsrfTokenServiceAsync; import com.google.gwt.user.client.ui.RootPanel; public final class Contacts implements com.google.gwt.core.client.EntryPoint { public void onModuleLoad() { final XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync) GWT.create( XsrfTokenService.class ); //noinspection GwtSetServiceEntryPointCalls ( (ServiceDefTarget) xsrf ).setServiceEntryPoint( GWT.getHostPageBaseURL() + "xsrf" ); - // Do something like the following if you ar enot using container based security + // Do something like the following if you are not using container based security //com.google.gwt.user.client.Cookies.setCookie( "JSESSIONID", "Any value you like for the XSRF Token creation" ); xsrf.getNewXsrfToken( new AsyncCallback<XsrfToken>() { public void onFailure( final Throwable caught ) { try { throw caught; } catch ( final RpcTokenException e ) { // Can be thrown for several reasons: // - duplicate session cookie, which may be a sign of a cookie // overwrite attack // - XSRF token cannot be generated because session cookie isn't // present } catch ( Throwable e ) { // unexpected } Window.alert( "Error generating security token. Please reload page." ); } public void onSuccess( final XsrfToken xsrfToken ) { ContactsServicesGinModule.setXsrfToken( xsrfToken ); startupApplication(); } } ); } private void startupApplication() { final ContactGinjector injector = GWT.create( ContactGinjector.class ); // Force the creation of the ActivityManager injector.getActivityManager(); RootPanel.get().add( injector.getMainPanel() ); // Goes to place represented on URL or default place injector.getPlaceHistoryHandler().handleCurrentHistory(); } }
true
true
public void onModuleLoad() { final XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync) GWT.create( XsrfTokenService.class ); //noinspection GwtSetServiceEntryPointCalls ( (ServiceDefTarget) xsrf ).setServiceEntryPoint( GWT.getHostPageBaseURL() + "xsrf" ); // Do something like the following if you ar enot using container based security //com.google.gwt.user.client.Cookies.setCookie( "JSESSIONID", "Any value you like for the XSRF Token creation" ); xsrf.getNewXsrfToken( new AsyncCallback<XsrfToken>() { public void onFailure( final Throwable caught ) { try { throw caught; } catch ( final RpcTokenException e ) { // Can be thrown for several reasons: // - duplicate session cookie, which may be a sign of a cookie // overwrite attack // - XSRF token cannot be generated because session cookie isn't // present } catch ( Throwable e ) { // unexpected } Window.alert( "Error generating security token. Please reload page." ); } public void onSuccess( final XsrfToken xsrfToken ) { ContactsServicesGinModule.setXsrfToken( xsrfToken ); startupApplication(); } } ); }
public void onModuleLoad() { final XsrfTokenServiceAsync xsrf = (XsrfTokenServiceAsync) GWT.create( XsrfTokenService.class ); //noinspection GwtSetServiceEntryPointCalls ( (ServiceDefTarget) xsrf ).setServiceEntryPoint( GWT.getHostPageBaseURL() + "xsrf" ); // Do something like the following if you are not using container based security //com.google.gwt.user.client.Cookies.setCookie( "JSESSIONID", "Any value you like for the XSRF Token creation" ); xsrf.getNewXsrfToken( new AsyncCallback<XsrfToken>() { public void onFailure( final Throwable caught ) { try { throw caught; } catch ( final RpcTokenException e ) { // Can be thrown for several reasons: // - duplicate session cookie, which may be a sign of a cookie // overwrite attack // - XSRF token cannot be generated because session cookie isn't // present } catch ( Throwable e ) { // unexpected } Window.alert( "Error generating security token. Please reload page." ); } public void onSuccess( final XsrfToken xsrfToken ) { ContactsServicesGinModule.setXsrfToken( xsrfToken ); startupApplication(); } } ); }
diff --git a/mmstudio/src/org/micromanager/MMStudioMainFrame.java b/mmstudio/src/org/micromanager/MMStudioMainFrame.java index d7642d655..a5f1779d0 100644 --- a/mmstudio/src/org/micromanager/MMStudioMainFrame.java +++ b/mmstudio/src/org/micromanager/MMStudioMainFrame.java @@ -1,4403 +1,4404 @@ /////////////////////////////////////////////////////////////////////////////// //FILE: MMStudioMainFrame.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- //AUTHOR: Nenad Amodaj, [email protected], Jul 18, 2005 //COPYRIGHT: University of California, San Francisco, 2006 // 100X Imaging Inc, www.100ximaging.com, 2008 //LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // This file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. //CVS: $Id$ // package org.micromanager; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.Line; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ImageStatistics; import ij.process.ShortProcessor; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpringLayout; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.LineBorder; import mmcorej.CMMCore; import mmcorej.DeviceType; import mmcorej.MMCoreJ; import mmcorej.MMEventCallback; import mmcorej.Metadata; import mmcorej.StrVector; import org.json.JSONObject; import org.micromanager.acquisition.AcquisitionManager; import org.micromanager.acquisition.MMAcquisitionSnap; import org.micromanager.acquisition.MMImageCache; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.Autofocus; import org.micromanager.api.DeviceControlGUI; import org.micromanager.api.MMPlugin; import org.micromanager.api.ScriptInterface; import org.micromanager.api.MMListenerInterface; import org.micromanager.conf.ConfiguratorDlg; import org.micromanager.conf.MMConfigFileException; import org.micromanager.conf.MicroscopeModel; import org.micromanager.graph.ContrastPanel; import org.micromanager.graph.GraphData; import org.micromanager.graph.GraphFrame; import org.micromanager.image5d.ChannelCalibration; import org.micromanager.image5d.ChannelControl; import org.micromanager.image5d.ChannelDisplayProperties; import org.micromanager.image5d.Crop_Image5D; import org.micromanager.image5d.Duplicate_Image5D; import org.micromanager.image5d.Image5D; import org.micromanager.image5d.Image5DWindow; import org.micromanager.image5d.Image5D_Channels_to_Stacks; import org.micromanager.image5d.Image5D_Stack_to_RGB; import org.micromanager.image5d.Image5D_Stack_to_RGB_t; import org.micromanager.image5d.Image5D_to_Stack; import org.micromanager.image5d.Image5D_to_VolumeViewer; import org.micromanager.image5d.Make_Montage; import org.micromanager.image5d.Split_Image5D; import org.micromanager.image5d.Z_Project; import org.micromanager.metadata.AcquisitionData; import org.micromanager.metadata.DisplaySettings; import org.micromanager.metadata.ImagePropertyKeys; import org.micromanager.metadata.MMAcqDataException; import org.micromanager.metadata.SummaryKeys; import org.micromanager.metadata.WellAcquisitionData; import org.micromanager.navigation.CenterAndDragListener; import org.micromanager.navigation.PositionList; import org.micromanager.navigation.XYZKeyListener; import org.micromanager.navigation.ZWheelListener; import org.micromanager.utils.Annotator; import org.micromanager.utils.AutofocusManager; import org.micromanager.utils.CfgFileFilter; import org.micromanager.utils.ContrastSettings; import org.micromanager.utils.GUIColors; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMImageWindow; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.TextUtils; import org.micromanager.utils.WaitDialog; import bsh.EvalError; import bsh.Interpreter; import com.swtdesigner.SwingResourceManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.process.ColorProcessor; import java.awt.Cursor; import java.awt.FileDialog; import java.awt.Graphics; import java.awt.image.DirectColorModel; import java.util.Collections; import java.util.Map; import mmcorej.TaggedImage; import org.micromanager.api.AcquisitionInterface; import org.micromanager.acquisition.AcquisitionWrapperEngine; import org.micromanager.utils.ReportingUtils; /* * Main panel and application class for the MMStudio. */ public class MMStudioMainFrame extends JFrame implements DeviceControlGUI, ScriptInterface { private static final String MICRO_MANAGER_TITLE = "Micro-Manager 1.4"; private static final String VERSION = "1.4.0 "; private static final long serialVersionUID = 3556500289598574541L; private static final String MAIN_FRAME_X = "x"; private static final String MAIN_FRAME_Y = "y"; private static final String MAIN_FRAME_WIDTH = "width"; private static final String MAIN_FRAME_HEIGHT = "height"; private static final String MAIN_EXPOSURE = "exposure"; private static final String SYSTEM_CONFIG_FILE = "sysconfig_file"; private static final String MAIN_STRETCH_CONTRAST = "stretch_contrast"; private static final String CONTRAST_SETTINGS_8_MIN = "contrast8_MIN"; private static final String CONTRAST_SETTINGS_8_MAX = "contrast8_MAX"; private static final String CONTRAST_SETTINGS_16_MIN = "contrast16_MIN"; private static final String CONTRAST_SETTINGS_16_MAX = "contrast16_MAX"; private static final String OPEN_ACQ_DIR = "openDataDir"; private static final String SCRIPT_CORE_OBJECT = "mmc"; private static final String SCRIPT_ACQENG_OBJECT = "acq"; private static final String SCRIPT_GUI_OBJECT = "gui"; private static final String AUTOFOCUS_DEVICE = "autofocus_device"; private static final String MOUSE_MOVES_STAGE = "mouse_moves_stage"; // cfg file saving private static final String CFGFILE_ENTRY_BASE = "CFGFileEntry"; // + {0, 1, 2, 3, 4} // GUI components private JComboBox comboBinning_; private JComboBox shutterComboBox_; private JTextField textFieldExp_; private SpringLayout springLayout_; private JLabel labelImageDimensions_; private JToggleButton toggleButtonLive_; private JCheckBox autoShutterCheckBox_; private boolean autoShutterOrg_; private boolean shutterOrg_; private MMOptions options_; private boolean runsAsPlugin_; private JCheckBoxMenuItem centerAndDragMenuItem_; private JButton buttonSnap_; private JButton buttonAutofocus_; private JButton buttonAutofocusTools_; private JToggleButton toggleButtonShutter_; private GUIColors guiColors_; private GraphFrame profileWin_; private PropertyEditor propertyBrowser_; private CalibrationListDlg calibrationListDlg_; private AcqControlDlg acqControlWin_; private ArrayList<PluginItem> plugins_; private List<MMListenerInterface> MMListeners_ = (List<MMListenerInterface>) Collections.synchronizedList(new ArrayList<MMListenerInterface>()); private List<Component> MMFrames_ = (List<Component>) Collections.synchronizedList(new ArrayList<Component>()); private AutofocusManager afMgr_; private final static String DEFAULT_CONFIG_FILE_NAME = "MMConfig_demo.cfg"; private ArrayList<String> MRUConfigFiles_; private static final int maxMRUCfgs_ = 5; private String sysConfigFile_; private String startupScriptFile_; private String sysStateFile_ = "MMSystemState.cfg"; private ConfigGroupPad configPad_; private ContrastPanel contrastPanel_; // Timer interval - image display interval private double liveModeInterval_ = 40; private Timer liveModeTimer_; private GraphData lineProfileData_; private Object img_; // labels for standard devices private String cameraLabel_; private String zStageLabel_; private String shutterLabel_; private String xyStageLabel_; // applications settings private Preferences mainPrefs_; private Preferences systemPrefs_; // MMcore private CMMCore core_; private AcquisitionEngine engine_; private PositionList posList_; private PositionListDlg posListDlg_; private String openAcqDirectory_ = ""; private boolean running_; private boolean liveRunning_ = false; private boolean configChanged_ = false; private StrVector shutters_ = null; private JButton saveConfigButton_; private FastAcqDlg fastAcqWin_; private ScriptPanel scriptPanel_; private SplitView splitView_; private CenterAndDragListener centerAndDragListener_; private ZWheelListener zWheelListener_; private XYZKeyListener xyzKeyListener_; private AcquisitionManager acqMgr_; private static MMImageWindow imageWin_; private int snapCount_ = -1; private boolean liveModeSuspended_; private boolean liveModeFullyStarted_; public Font defaultScriptFont_ = null; public static MMImageWindow getLiveWin() { return imageWin_; } // Our instance private MMStudioMainFrame gui_; // Callback private CoreEventCallback cb_; private JMenuBar menuBar_; private ConfigPadButtonPanel configPadButtonPanel_; private boolean virtual_ = false; private final JMenu switchConfigurationMenu_; private void applyChannelSettingsTo5D(AcquisitionData ad, Image5D img5d) throws MMAcqDataException { Color[] colors = ad.getChannelColors(); String[] names = ad.getChannelNames(); if (colors != null && names != null) { for (int i = 0; i < ad.getNumberOfChannels(); i++) { ChannelCalibration chcal = new ChannelCalibration(); // set channel name chcal.setLabel(names[i]); img5d.setChannelCalibration(i + 1, chcal); if (img5d.getBytesPerPixel() == 4) { img5d.setChannelColorModel(i + 1, new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF)); } else { img5d.setChannelColorModel(i + 1, ChannelDisplayProperties.createModelFromColor(colors[i])); } } } } private void popUpImage5DWindow(Image5D img5d, AcquisitionData ad) { // pop-up 5d image window Image5DWindow i5dWin = new Image5DWindow(img5d); i5dWin.setBackground(guiColors_.background.get(options_.displayBackground)); if (ad.getNumberOfChannels() == 1) { int modee = ChannelControl.ONE_CHANNEL_COLOR; if( null != img5d){ if( img5d.getProcessor() instanceof ColorProcessor ) modee = ChannelControl.RGB; } img5d.setDisplayMode(modee); } else { img5d.setDisplayMode(ChannelControl.OVERLAY); } i5dWin.setAcquitionEngine(engine_); i5dWin.setAcquisitionData(ad); i5dWin.setAcqSavePath(openAcqDirectory_); img5d.changes = false; } private void set5DDisplaySettingsForChannels(int k, int i, AcquisitionData ad, int j, Image5D img5d) throws MMAcqDataException { // set display settings for channels if (k == 0 && i == 0) { DisplaySettings[] ds = ad.getChannelDisplaySettings(); if (ds != null) { // display properties are recorded in // metadata use them... double min = ds[j].min; double max = ds[j].max; img5d.setChannelMinMax(j + 1, min, max); } else { // ...if not, autoscale channels based // on the first slice of the first frame ImageStatistics stats = img5d.getStatistics(); // get // uncalibrated // stats double min = stats.min; double max = stats.max; img5d.setChannelMinMax(j + 1, min, max); } } } public ImageWindow getImageWin() { return imageWin_; } private void updateSwitchConfigurationMenu() { switchConfigurationMenu_.removeAll(); for (final String configFile : MRUConfigFiles_) { if (! configFile.equals(sysConfigFile_)) { JMenuItem configMenuItem = new JMenuItem(); configMenuItem.setText(configFile); configMenuItem.addActionListener(new ActionListener() { String theConfigFile = configFile; public void actionPerformed(ActionEvent e) { sysConfigFile_ = theConfigFile; loadSystemConfiguration(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); } }); switchConfigurationMenu_.add(configMenuItem); } } } /** * Allows MMListeners to register themselves */ public void addMMListener(MMListenerInterface newL) { if (MMListeners_.contains(newL)) return; MMListeners_.add(newL); } /** * Allows MMListeners to remove themselves */ public void removeMMListener(MMListenerInterface oldL) { if (!MMListeners_.contains(oldL)) return; MMListeners_.remove(oldL); } /** * Lets JComponents register themselves so that their background can be * manipulated */ public void addMMBackgroundListener(Component comp) { if (MMFrames_.contains(comp)) return; MMFrames_.add(comp); } /** * Lets JComponents remove themselves from the list whose background gets * changes */ public void removeMMBackgroundListener(Component comp) { if (!MMFrames_.contains(comp)) return; MMFrames_.remove(comp); } public void setAcquisitionEngine(String acqName, AcquisitionEngine eng) { this.acqMgr_.setAcquisitionEngine(acqName, eng); } public void updateContrast(ImagePlus iplus) { contrastPanel_.updateContrast(iplus); } public void setAcquisitionCache(String acqName, MMImageCache imageCache) { this.acqMgr_.setAcquisitionCache(acqName, imageCache); } /** * Callback to update GUI when a change happens in the MMCore. */ public class CoreEventCallback extends MMEventCallback { public CoreEventCallback() { super(); } @Override public void onPropertiesChanged() { // TODO: remove test once acquisition engine is fully multithreaded if (engine_ != null && engine_.isAcquisitionRunning()) { core_.logMessage("Notification from MMCore ignored because acquistion is running!"); } else { updateGUI(true); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertiesChangedAlert(); } core_.logMessage("Notification from MMCore!"); } } @Override public void onPropertyChanged(String deviceName, String propName, String propValue) { core_.logMessage("Notification for Device: " + deviceName + " Property: " + propName + " changed to value: " + propValue); // update all registered listeners for (MMListenerInterface mmIntf:MMListeners_) { mmIntf.propertyChangedAlert(deviceName, propName, propValue); } } @Override public void onConfigGroupChanged(String groupName, String newConfig) { try { configPad_.refreshGroup(groupName, newConfig); } catch (Exception e) { } } @Override public void onPixelSizeChanged(double newPixelSizeUm) { updatePixSizeUm (newPixelSizeUm); } @Override public void onStagePositionChanged(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPos(pos); } @Override public void onStagePositionChangedRelative(String deviceName, double pos) { if (deviceName.equals(zStageLabel_)) updateZPosRelative(pos); } @Override public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPos(xPos, yPos); } @Override public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) { if (deviceName.equals(xyStageLabel_)) updateXYPosRelative(xPos, yPos); } } private class PluginItem { public Class<?> pluginClass = null; public String menuItem = "undefined"; public MMPlugin plugin = null; public String className = ""; public void instantiate() { try { if (plugin == null) { plugin = (MMPlugin) pluginClass.newInstance(); } } catch (InstantiationException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } plugin.setApp(MMStudioMainFrame.this); } } /* * Simple class used to cache static info */ private class StaticInfo { public long width_; public long height_; public long bytesPerPixel_; public long imageBitDepth_; public double pixSizeUm_; public double zPos_; public double x_; public double y_; } private StaticInfo staticInfo_ = new StaticInfo(); /** * Main procedure for stand alone operation. */ public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); MMStudioMainFrame frame = new MMStudioMainFrame(false); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } catch (Throwable e) { ReportingUtils.showError(e, "A java error has caused Micro-Manager to exit."); System.exit(1); } } public MMStudioMainFrame(boolean pluginStatus) { super(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { ReportingUtils.showError(e, "An uncaught exception was thrown in thread " + t.getName() + "."); } }); options_ = new MMOptions(); options_.loadSettings(); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; // !!! contrastSettings8_ = new ContrastSettings(); // contrastSettings16_ = new ContrastSettings(); acqMgr_ = new AcquisitionManager(); sysConfigFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME); if (options_.startupScript.length() > 0) { startupScriptFile_ = new String(System.getProperty("user.dir") + "/" + options_.startupScript); } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); systemPrefs_ = mainPrefs_; // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } // initialize timer ActionListener liveModeTimerHandler = new ActionListener() { public void actionPerformed(ActionEvent evt) { + Thread.currentThread().setPriority(3); if (!isImageWindowOpen()) { // stop live acquisition if user closed the window enableLiveMode(false); return; } if (!isNewImageAvailable()) { return; } try { Object img; if (!liveModeFullyStarted_) { if (core_.getRemainingImageCount() > 0) { liveModeFullyStarted_ = true; } } if (liveModeFullyStarted_) { img = core_.getLastImage(); if (img != img_) { img_ = img; displayImage(img_); } } } catch (Exception e) { ReportingUtils.showError(e); return; } } }; liveModeTimer_ = new Timer((int) liveModeInterval_, liveModeTimerHandler); liveModeTimer_.stop(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 451); boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); setBounds(x, y, width, height); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); springLayout_ = new SpringLayout(); getContentPane().setLayout(springLayout_); setTitle(MICRO_MANAGER_TITLE); setBackground(guiColors_.background.get((options_.displayBackground))); // Snap button // ----------- buttonSnap_ = new JButton(); buttonSnap_.setIconTextGap(6); buttonSnap_.setText("Snap"); buttonSnap_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonSnap_.setToolTipText("Snap single image"); buttonSnap_.setMaximumSize(new Dimension(0, 0)); buttonSnap_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); getContentPane().add(buttonSnap_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap_, 4, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonSnap_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonSnap_, 7, SpringLayout.WEST, getContentPane()); // Initialize // ---------- // Exposure field // --------------- final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); getContentPane().add(label_1); springLayout_.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, getContentPane()); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { setExposure(); } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExposure(); } }); getContentPane().add(textFieldExp_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 276, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, getContentPane()); // Live button // ----------- toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2)); toggleButtonLive_.setIconTextGap(1); toggleButtonLive_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuous live view"); toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!IsLiveModeOn()) { // Display interval for Live Mode changes as well setLiveModeInterval(); } enableLiveMode(!IsLiveModeOn()); } }); toggleButtonLive_.setText("Live"); getContentPane().add(toggleButtonLive_); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, getContentPane()); // Acquire button // ----------- JButton acquireButton = new JButton(); acquireButton.setMargin(new Insets(2, 2, 2, 2)); acquireButton.setIconTextGap(1); acquireButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/snapAppend.png")); acquireButton.setIconTextGap(6); acquireButton.setToolTipText("Acquire single frame"); acquireButton.setFont(new Font("Arial", Font.PLAIN, 10)); acquireButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { snapAndAddToImage5D(null); } }); acquireButton.setText("Acquire"); getContentPane().add(acquireButton); springLayout_.putConstraint(SpringLayout.SOUTH, acquireButton, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, acquireButton, 48, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, acquireButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, acquireButton, 7, SpringLayout.WEST, getContentPane()); // Shutter button // -------------- toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { if (toggleButtonShutter_.isSelected()) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); getContentPane().add(toggleButtonShutter_); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138 - 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117 - 21, SpringLayout.NORTH, getContentPane()); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); getContentPane().add(activeShutterLabel); springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel, 160 - 2, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel, 113 - 2, SpringLayout.WEST, getContentPane()); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } return; } }); getContentPane().add(shutterComboBox_); springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, getContentPane()); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(); } }.start(); } }); openMenuItem.setText("Open Acquisition Data..."); fileMenu.add(openMenuItem); fileMenu.addSeparator(); final JMenuItem loadState = new JMenuItem(); loadState.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystemState(); } }); loadState.setText("Load System State..."); fileMenu.add(loadState); final JMenuItem saveStateAs = new JMenuItem(); fileMenu.add(saveStateAs); saveStateAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystemState(); } }); saveStateAs.setText("Save System State As..."); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); final JMenu image5dMenu = new JMenu(); image5dMenu.setText("Image5D"); menuBar_.add(image5dMenu); final JMenuItem closeAllMenuItem = new JMenuItem(); closeAllMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { WindowManager.closeAllWindows(); } }); closeAllMenuItem.setText("Close All"); image5dMenu.add(closeAllMenuItem); final JMenuItem duplicateMenuItem = new JMenuItem(); duplicateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Duplicate_Image5D duplicate = new Duplicate_Image5D(); duplicate.run(""); } }); duplicateMenuItem.setText("Duplicate"); image5dMenu.add(duplicateMenuItem); final JMenuItem cropMenuItem = new JMenuItem(); cropMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Crop_Image5D crop = new Crop_Image5D(); crop.run(""); } }); cropMenuItem.setText("Crop"); image5dMenu.add(cropMenuItem); final JMenuItem makeMontageMenuItem = new JMenuItem(); makeMontageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Make_Montage makeMontage = new Make_Montage(); makeMontage.run(""); } }); makeMontageMenuItem.setText("Make Montage"); image5dMenu.add(makeMontageMenuItem); final JMenuItem zProjectMenuItem = new JMenuItem(); zProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Z_Project projection = new Z_Project(); projection.run(""); } }); zProjectMenuItem.setText("Z Project"); image5dMenu.add(zProjectMenuItem); final JMenuItem convertToRgbMenuItem = new JMenuItem(); convertToRgbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB(); stackToRGB.run(""); } }); convertToRgbMenuItem.setText("Copy to RGB Stack(z)"); image5dMenu.add(convertToRgbMenuItem); final JMenuItem convertToRgbtMenuItem = new JMenuItem(); convertToRgbtMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t(); stackToRGB_t.run(""); } }); convertToRgbtMenuItem.setText("Copy to RGB Stack(t)"); image5dMenu.add(convertToRgbtMenuItem); final JMenuItem convertToStackMenuItem = new JMenuItem(); convertToStackMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_Stack image5DToStack = new Image5D_to_Stack(); image5DToStack.run(""); } }); convertToStackMenuItem.setText("Copy to Stack"); image5dMenu.add(convertToStackMenuItem); final JMenuItem convertToStacksMenuItem = new JMenuItem(); convertToStacksMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks(); image5DToStacks.run(""); } }); convertToStacksMenuItem.setText("Copy to Stacks (channels)"); image5dMenu.add(convertToStacksMenuItem); final JMenuItem volumeViewerMenuItem = new JMenuItem(); volumeViewerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer(); volumeViewer.run(""); } }); volumeViewerMenuItem.setText("VolumeViewer"); image5dMenu.add(volumeViewerMenuItem); final JMenuItem splitImageMenuItem = new JMenuItem(); splitImageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Split_Image5D splitImage = new Split_Image5D(); splitImage.run(""); } }); splitImageMenuItem.setText("SplitView"); image5dMenu.add(splitImageMenuItem); final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createScriptPanel(); } }); scriptPanelMenuItem.setText("Script Panel..."); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Multi-Dimensional Acquisition..."); toolsMenu.add(acquisitionMenuItem); final JMenuItem sequenceMenuItem = new JMenuItem(); sequenceMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); sequenceMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film_go.png")); sequenceMenuItem.setText("Burst Acquisition..."); toolsMenu.add(sequenceMenuItem); final JMenuItem splitViewMenuItem = new JMenuItem(); splitViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitViewDialog(); } }); splitViewMenuItem.setText("Split View..."); toolsMenu.add(splitViewMenuItem); centerAndDragMenuItem_ = new JCheckBoxMenuItem(); centerAndDragMenuItem_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (centerAndDragListener_ == null) { centerAndDragListener_ = new CenterAndDragListener(core_, gui_); } if (!centerAndDragListener_.isRunning()) { centerAndDragListener_.start(); centerAndDragMenuItem_.setSelected(true); } else { centerAndDragListener_.stop(); centerAndDragMenuItem_.setSelected(false); } mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }); centerAndDragMenuItem_.setText("Mouse Moves Stage"); centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); toolsMenu.add(centerAndDragMenuItem_); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_); configurator.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = configurator.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); } catch (Exception e) { ReportingUtils.showError(e); return; } } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadConfiguration(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); switchConfigurationMenu_ = new JMenu(); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Settings..."); toolsMenu.add(saveConfigurationPresetsMenuItem); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; final JMenuItem optionsMenuItem = new JMenuItem(); optionsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); getContentPane().add(binningLabel); springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 64, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1, SpringLayout.WEST, getContentPane()); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(labelImageDimensions_); springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, -5, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -25, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, getContentPane()); comboBinning_ = new JComboBox(); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeBinning(); } }); getContentPane().add(comboBinning_); springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 66, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 43, SpringLayout.NORTH, getContentPane()); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); getContentPane().add(cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, getContentPane()); configPad_ = new ConfigGroupPad(); configPad_.setFont(new Font("", Font.PLAIN, 10)); getContentPane().add(configPad_); springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 156, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, getContentPane()); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(this); getContentPane().add(configPadButtonPanel_); springLayout_.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, 158, SpringLayout.NORTH, getContentPane()); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration settings"); getContentPane().add(stateDeviceLabel); springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0, SpringLayout.SOUTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0, SpringLayout.NORTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150, SpringLayout.WEST, configPad_); springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0, SpringLayout.WEST, configPad_); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open Acquistion dialog"); buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Multi-D Acq."); getContentPane().add(buttonAcqSetup); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, getContentPane()); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.setAutoShutter(autoShutterCheckBox_.isSelected()); if (shutterLabel_.length() > 0) { try { setShutterButton(core_.getShutterOpen()); } catch (Exception e1) { ReportingUtils.showError(e1); } } if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); getContentPane().add(autoShutterCheckBox_); springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118 - 22, SpringLayout.NORTH, getContentPane()); final JButton burstButton = new JButton(); burstButton.setMargin(new Insets(2, 2, 2, 2)); burstButton.setIconTextGap(1); burstButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/film_go.png")); burstButton.setFont(new Font("Arial", Font.PLAIN, 10)); burstButton.setToolTipText("Open Burst dialog for fast sequence acquisition"); burstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); burstButton.setText("Burst"); getContentPane().add(burstButton); springLayout_.putConstraint(SpringLayout.SOUTH, burstButton, 113, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, burstButton, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, burstButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, burstButton, 7, SpringLayout.WEST, getContentPane()); final JButton refreshButton = new JButton(); refreshButton.setMargin(new Insets(2, 2, 2, 2)); refreshButton.setIconTextGap(1); refreshButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 135, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 114, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, getContentPane()); // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { running_ = false; closeSequence(); } @Override public void windowOpened(WindowEvent e) { // ------------------- // initialize hardware // ------------------- core_ = new CMMCore(); ReportingUtils.setCore(core_); core_.enableDebugLog(options_.debugLogEnabled); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version")); cameraLabel_ = new String(""); shutterLabel_ = new String(""); zStageLabel_ = new String(""); xyStageLabel_ = new String(""); engine_ = new AcquisitionWrapperEngine(); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); if (!options_.doNotAskForConfigFile) { MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); afMgr_ = new AutofocusManager(core_); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); loadPlugins(); toFront(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls initializeGUI(); initializePluginMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } // switch error reporting back on ReportingUtils.showErrorOn(true); } }); final JButton setRoiButton = new JButton(); setRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setROI(); } }); getContentPane().add(setRoiButton); springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 37, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JButton clearRoiButton = new JButton(); clearRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearROI(); } }); getContentPane().add(clearRoiButton); springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 70, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 40, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); getContentPane().add(regionOfInterestLabel); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, getContentPane()); contrastPanel_ = new ContrastPanel(); contrastPanel_.setFont(new Font("", Font.PLAIN, 10)); contrastPanel_.setContrastStretch(stretch); contrastPanel_.setBorder(new LineBorder(Color.black, 1, false)); getContentPane().add(contrastPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7, SpringLayout.WEST, getContentPane()); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); getContentPane().add(regionOfInterestLabel_1); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 139, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 81, SpringLayout.WEST, getContentPane()); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setToolTipText("Zoom in"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomInButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 110, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 80, SpringLayout.WEST, getContentPane()); final JButton zoomOutButton = new JButton(); zoomOutButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Zoom out"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomOutButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 143, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 113, SpringLayout.WEST, getContentPane()); // Profile // ------- final JLabel profileLabel_ = new JLabel(); profileLabel_.setFont(new Font("Arial", Font.BOLD, 11)); profileLabel_.setText("Profile"); getContentPane().add(profileLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, profileLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, profileLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, profileLabel_, 217, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, profileLabel_, 154, SpringLayout.WEST, getContentPane()); final JButton buttonProf = new JButton(); buttonProf.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); buttonProf.setFont(new Font("Arial", Font.PLAIN, 10)); buttonProf.setToolTipText("Open line profile window (requires line selection)"); buttonProf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); // buttonProf.setText("Profile"); getContentPane().add(buttonProf); springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 183, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 153, SpringLayout.WEST, getContentPane()); // Autofocus // ------- final JLabel autofocusLabel_ = new JLabel(); autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11)); autofocusLabel_.setText("Autofocus"); getContentPane().add(autofocusLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, autofocusLabel_, 274, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autofocusLabel_, 194, SpringLayout.WEST, getContentPane()); buttonAutofocus_ = new JButton(); buttonAutofocus_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/find.png")); buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocus_.setToolTipText("Autofocus now"); buttonAutofocus_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (afMgr_.getDevice() != null) { try { afMgr_.getDevice().fullFocus(); // or any other method from Autofocus.java API } catch (MMException mE) { ReportingUtils.showError(mE); } } } }); getContentPane().add(buttonAutofocus_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193, SpringLayout.WEST, getContentPane()); buttonAutofocusTools_ = new JButton(); buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/wrench_orange.png")); buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocusTools_.setToolTipText("Set autofocus options"); buttonAutofocusTools_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAutofocusDialog(); } }); getContentPane().add(buttonAutofocusTools_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226, SpringLayout.WEST, getContentPane()); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); getContentPane().add(saveConfigButton_); springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, -80, SpringLayout.EAST, getContentPane()); } private void handleException(Exception e, String msg) { String errText = "Exception occurred: "; if (msg.length() > 0) { errText += msg + " -- "; } if (options_.debugLogEnabled) { errText += e.getMessage(); } else { errText += e.toString() + "\n"; ReportingUtils.showError(e); } handleError(errText); } private void handleException(Exception e) { handleException(e, ""); } private void handleError(String message) { if (IsLiveModeOn()) { // Should we always stop live mode on any error? enableLiveMode(false); } JOptionPane.showMessageDialog(this, message); core_.logMessage(message); } public void makeActive() { toFront(); } private void setExposure() { try { core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText())); // Display the new exposure time double exposure = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); // Interval for Live Mode changes as well setLiveModeInterval(); } catch (Exception exp) { // Do nothing. } } private void updateTitle() { this.setTitle("System: " + sysConfigFile_); } private void updateLineProfile() { if (!isImageWindowOpen() || profileWin_ == null || !profileWin_.isShowing()) { return; } calculateLineProfileData(imageWin_.getImagePlus()); profileWin_.setData(lineProfileData_); } private void openLineProfileWindow() { if (imageWin_ == null || imageWin_.isClosed()) { return; } calculateLineProfileData(imageWin_.getImagePlus()); if (lineProfileData_ == null) { return; } profileWin_ = new GraphFrame(); profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); profileWin_.setData(lineProfileData_); profileWin_.setAutoScale(); profileWin_.setTitle("Live line profile"); profileWin_.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(profileWin_); profileWin_.setVisible(true); } public Rectangle getROI() throws Exception { // ROI values are give as x,y,w,h in individual one-member arrays (pointers in C++): int[][] a = new int[4][1]; core_.getROI(a[0], a[1], a[2], a[3]); // Return as a single array with x,y,w,h: return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]); } private void calculateLineProfileData(ImagePlus imp) { // generate line profile Roi roi = imp.getRoi(); if (roi == null || !roi.isLine()) { // if there is no line ROI, create one Rectangle r = imp.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iXROI += iWidth / 2; iYROI += iHeight / 2; } roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI + iWidth / 4, iYROI + iHeight / 4); imp.setRoi(roi); roi = imp.getRoi(); } ImageProcessor ip = imp.getProcessor(); ip.setInterpolate(true); Line line = (Line) roi; if (lineProfileData_ == null) { lineProfileData_ = new GraphData(); } lineProfileData_.setData(line.getPixels()); } public void setROI(Rectangle r) throws Exception { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } core_.setROI(r.x, r.y, r.width, r.height); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } private void setROI() { ImagePlus curImage = WindowManager.getCurrentImage(); if (curImage == null) { return; } Roi roi = curImage.getRoi(); try { if (roi == null) { // if there is no ROI, create one Rectangle r = curImage.getProcessor().getRoi(); int iWidth = r.width; int iHeight = r.height; int iXROI = r.x; int iYROI = r.y; if (roi == null) { iWidth /= 2; iHeight /= 2; iXROI += iWidth / 2; iYROI += iHeight / 2; } curImage.setRoi(iXROI, iYROI, iWidth, iHeight); roi = curImage.getRoi(); } if (roi.getType() != Roi.RECTANGLE) { handleError("ROI must be a rectangle.\nUse the ImageJ rectangle tool to draw the ROI."); return; } Rectangle r = roi.getBoundingRect(); // Stop (and restart) live mode if it is running setROI(r); } catch (Exception e) { ReportingUtils.showError(e); } } private void clearROI() { try { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } core_.clearROI(); updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private BooleanLock creatingImageWindow_ = new BooleanLock(false); private static long waitForCreateImageWindowTimeout_ = 5000; private MMImageWindow createImageWindow() { if (creatingImageWindow_.isTrue()) { try { creatingImageWindow_.waitToSetFalse(waitForCreateImageWindowTimeout_); } catch (Exception e) { ReportingUtils.showError(e); } return imageWin_; } creatingImageWindow_.setValue(true); MMImageWindow win = imageWin_; removeMMBackgroundListener(imageWin_); imageWin_ = null; try { if (win != null) { win.saveAttributes(); // WindowManager.removeWindow(win); // win.close(); win.dispose(); win = null; } win = new MMImageWindow(core_, this); core_.logMessage("createImageWin1"); win.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(win); setIJCal(win); // listeners if (centerAndDragListener_ != null && centerAndDragListener_.isRunning()) { centerAndDragListener_.attach(win.getImagePlus().getWindow()); } if (zWheelListener_ != null && zWheelListener_.isRunning()) { zWheelListener_.attach(win.getImagePlus().getWindow()); } if (xyzKeyListener_ != null && xyzKeyListener_.isRunning()) { xyzKeyListener_.attach(win.getImagePlus().getWindow()); } win.getCanvas().requestFocus(); imageWin_ = win; } catch (Exception e) { if (win != null) { win.saveAttributes(); WindowManager.removeWindow(win); win.dispose(); } ReportingUtils.showError(e); } creatingImageWindow_.setValue(false); return imageWin_; } /** * Returns instance of the core uManager object; */ public CMMCore getMMCore() { return core_; } public void saveConfigPresets() { MicroscopeModel model = new MicroscopeModel(); try { model.loadFromFile(sysConfigFile_); model.createSetupConfigsFromHardware(core_); model.createResolutionsFromHardware(core_); JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(model.getFileName())); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if (f.exists()) { int sel = JOptionPane.showConfirmDialog(this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if (sel == JOptionPane.YES_OPTION) { saveFile = true; } else { saveFile = false; } } } else { return; } } while (saveFile == false); model.saveToFile(f.getAbsolutePath()); sysConfigFile_ = f.getAbsolutePath(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); updateTitle(); } catch (MMConfigFileException e) { ReportingUtils.showError(e); } } protected void setConfigSaveButtonStatus(boolean changed) { saveConfigButton_.setEnabled(changed); } private File runAcquisitionBrowser() { File selectedFile = null; if (JavaUtils.isMac()) { System.setProperty("apple.awt.fileDialogForDirectories", "true"); FileDialog fd = new FileDialog(this); fd.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); if (fd.getFile() != null) { selectedFile = new File(fd.getDirectory() + "/" + fd.getFile()); } } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = fc.getSelectedFile(); } } return selectedFile; } /** * Open an existing acquisition directory and build image5d window. * */ protected void openAcquisitionData() { // choose the directory // -------------------- File f = runAcquisitionBrowser(); if (f != null) { if (f.isDirectory()) { openAcqDirectory_ = f.getAbsolutePath(); } else { openAcqDirectory_ = f.getParent(); } String rootDir = new File(openAcqDirectory_).getAbsolutePath(); String name = new File(openAcqDirectory_).getName(); try { openAcquisition(name, rootDir); } catch (MMScriptException ex) { ReportingUtils.showError(ex); } } } protected void zoomOut() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomOut(r.width / 2, r.height / 2); } } protected void zoomIn() { ImageWindow curWin = WindowManager.getCurrentWindow(); if (curWin != null) { ImageCanvas canvas = curWin.getCanvas(); Rectangle r = canvas.getBounds(); canvas.zoomIn(r.width / 2, r.height / 2); } } protected void changeBinning() { try { boolean liveRunning = false; if (liveRunning_) { liveRunning = liveRunning_; enableLiveMode(false); } if (isCameraAvailable()) { Object item = comboBinning_.getSelectedItem(); if (item != null) { core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString()); } } updateStaticInfo(); if (liveRunning) { enableLiveMode(true); } } catch (Exception e) { ReportingUtils.showError(e); } } private void createPropertyEditor() { if (propertyBrowser_ != null) { propertyBrowser_.dispose(); } propertyBrowser_ = new PropertyEditor(); propertyBrowser_.setGui(this); propertyBrowser_.setVisible(true); propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); propertyBrowser_.setCore(core_); } private void createCalibrationListDlg() { if (calibrationListDlg_ != null) { calibrationListDlg_.dispose(); } calibrationListDlg_ = new CalibrationListDlg(core_); calibrationListDlg_.setVisible(true); calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); calibrationListDlg_.setParentGUI(this); } public CalibrationListDlg getCalibrationListDlg() { if (calibrationListDlg_ == null) { createCalibrationListDlg(); } return calibrationListDlg_; } private void createScriptPanel() { if (scriptPanel_ == null) { scriptPanel_ = new ScriptPanel(core_, options_, this); scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_); scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_); scriptPanel_.setParentGUI(this); scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground))); addMMBackgroundListener(scriptPanel_); } scriptPanel_.setVisible(true); } /** * Updates Status line in main window from cached values */ private void updateStaticInfoFromCache() { String dimText = "Image size: " + staticInfo_.width_ + " X " + staticInfo_.height_ + " X " + staticInfo_.bytesPerPixel_ + ", Intensity range: " + staticInfo_.imageBitDepth_ + " bits"; dimText += ", " + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + "nm/pix"; if (zStageLabel_.length() > 0) { dimText += ", Z=" + TextUtils.FMT2.format(staticInfo_.zPos_) + "um"; } if (xyStageLabel_.length() > 0) { dimText += ", XY=(" + TextUtils.FMT2.format(staticInfo_.x_) + "," + TextUtils.FMT2.format(staticInfo_.y_) + ")um"; } labelImageDimensions_.setText(dimText); } public void updateXYPos(double x, double y) { staticInfo_.x_ = x; staticInfo_.y_ = y; updateStaticInfoFromCache(); } public void updateZPos(double z) { staticInfo_.zPos_ = z; updateStaticInfoFromCache(); } public void updateXYPosRelative(double x, double y) { staticInfo_.x_ += x; staticInfo_.y_ += y; updateStaticInfoFromCache(); } public void updateZPosRelative(double z) { staticInfo_.zPos_ += z; updateStaticInfoFromCache(); } public void updateXYStagePosition(){ double x[] = new double[1]; double y[] = new double[1]; try { if (xyStageLabel_.length() > 0) core_.getXYPosition(xyStageLabel_, x, y); } catch (Exception e) { ReportingUtils.showError(e); } staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void updatePixSizeUm (double pixSizeUm) { staticInfo_.pixSizeUm_ = pixSizeUm; updateStaticInfoFromCache(); } private void updateStaticInfo() { double zPos = 0.0; double x[] = new double[1]; double y[] = new double[1]; try { if (zStageLabel_.length() > 0) { zPos = core_.getPosition(zStageLabel_); } if (xyStageLabel_.length() > 0) { core_.getXYPosition(xyStageLabel_, x, y); } } catch (Exception e) { handleException(e); } staticInfo_.width_ = core_.getImageWidth(); staticInfo_.height_ = core_.getImageHeight(); staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel(); staticInfo_.imageBitDepth_ = core_.getImageBitDepth(); staticInfo_.pixSizeUm_ = core_.getPixelSizeUm(); staticInfo_.zPos_ = zPos; staticInfo_.x_ = x[0]; staticInfo_.y_ = y[0]; updateStaticInfoFromCache(); } private void setShutterButton(boolean state) { if (state) { toggleButtonShutter_.setSelected(true); toggleButtonShutter_.setText("Close"); } else { toggleButtonShutter_.setSelected(false); toggleButtonShutter_.setText("Open"); } } // ////////////////////////////////////////////////////////////////////////// // public interface available for scripting access // ////////////////////////////////////////////////////////////////////////// public void snapSingleImage() { doSnap(); } public Object getPixels() { if (imageWin_ != null) { return imageWin_.getImagePlus().getProcessor().getPixels(); } return null; } public void setPixels(Object obj) { if (imageWin_ == null) { return; } imageWin_.getImagePlus().getProcessor().setPixels(obj); } public int getImageHeight() { if (imageWin_ != null) { return imageWin_.getImagePlus().getHeight(); } return 0; } public int getImageWidth() { if (imageWin_ != null) { return imageWin_.getImagePlus().getWidth(); } return 0; } public int getImageDepth() { if (imageWin_ != null) { return imageWin_.getImagePlus().getBitDepth(); } return 0; } public ImageProcessor getImageProcessor() { if (imageWin_ == null) { return null; } return imageWin_.getImagePlus().getProcessor(); } private boolean isCameraAvailable() { return cameraLabel_.length() > 0; } public boolean isImageWindowOpen() { boolean ret = imageWin_ != null; ret = ret && !imageWin_.isClosed(); if (ret) { try { Graphics g = imageWin_.getGraphics(); if (null != g) { int ww = imageWin_.getWidth(); g.clearRect(0, 0, ww, 40); imageWin_.drawInfo(g); } else { // explicitly clean up if Graphics is null, rather // than cleaning up in the exception handler below.. WindowManager.removeWindow(imageWin_); imageWin_.saveAttributes(); imageWin_.dispose(); imageWin_ = null; ret = false; } } catch (Exception e) { WindowManager.removeWindow(imageWin_); imageWin_.saveAttributes(); imageWin_.dispose(); imageWin_ = null; ReportingUtils.showError(e); ret = false; } } return ret; } boolean IsLiveModeOn() { return liveModeTimer_ != null && liveModeTimer_.isRunning(); } public void enableLiveMode(boolean enable) { if (enable) { if (IsLiveModeOn()) { return; } try { if (!isImageWindowOpen() && creatingImageWindow_.isFalse()) { imageWin_ = createImageWindow(); } // this is needed to clear the subtitle, should be folded into // drawInfo imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40); imageWin_.drawInfo(imageWin_.getGraphics()); imageWin_.toFront(); // turn off auto shutter and open the shutter autoShutterOrg_ = core_.getAutoShutter(); if (shutterLabel_.length() > 0) { shutterOrg_ = core_.getShutterOpen(); } core_.setAutoShutter(false); // Hide the autoShutter Checkbox autoShutterCheckBox_.setEnabled(false); shutterLabel_ = core_.getShutterDevice(); // only open the shutter when we have one and the Auto shutter // checkbox was checked if ((shutterLabel_.length() > 0) && autoShutterOrg_) { core_.setShutterOpen(true); } // attach mouse wheel listener to control focus: if (zWheelListener_ == null) { zWheelListener_ = new ZWheelListener(core_, this); } zWheelListener_.start(imageWin_); // attach key listener to control the stage and focus: if (xyzKeyListener_ == null) { xyzKeyListener_ = new XYZKeyListener(core_, this); } xyzKeyListener_.start(imageWin_); // Do not display more often than dictated by the exposure time setLiveModeInterval(); liveModeFullyStarted_ = false; core_.startContinuousSequenceAcquisition(0.0); liveModeTimer_.start(); // Only hide the shutter checkbox if we are in autoshuttermode buttonSnap_.setEnabled(false); if (autoShutterOrg_) { toggleButtonShutter_.setEnabled(false); } imageWin_.setSubTitle("Live (running)"); liveRunning_ = true; } catch (Exception err) { ReportingUtils.showError(err, "Failed to enable live mode."); if (imageWin_ != null) { imageWin_.saveAttributes(); WindowManager.removeWindow(imageWin_); imageWin_.dispose(); imageWin_ = null; } } } else { if (!IsLiveModeOn()) { return; } try { liveModeTimer_.stop(); core_.stopSequenceAcquisition(); if (zWheelListener_ != null) { zWheelListener_.stop(); } if (xyzKeyListener_ != null) { xyzKeyListener_.stop(); } // restore auto shutter and close the shutter if (shutterLabel_.length() > 0) { core_.setShutterOpen(shutterOrg_); } core_.setAutoShutter(autoShutterOrg_); if (autoShutterOrg_) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } liveRunning_ = false; buttonSnap_.setEnabled(true); autoShutterCheckBox_.setEnabled(true); while (liveModeTimer_.isRunning()); // Make sure Timer properly stops. // This is here to avoid crashes when changing ROI in live mode // with Sensicam // Should be removed when underlying problem is dealt with Thread.sleep(100); imageWin_.setSubTitle("Live (stopped)"); } catch (Exception err) { ReportingUtils.showError(err, "Failed to disable live mode."); if (imageWin_ != null) { WindowManager.removeWindow(imageWin_); imageWin_.dispose(); imageWin_ = null; } } } toggleButtonLive_.setIcon(IsLiveModeOn() ? SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setSelected(IsLiveModeOn()); toggleButtonLive_.setText(IsLiveModeOn() ? "Stop Live" : "Live"); } public boolean getLiveMode() { return liveRunning_; } public boolean updateImage() { try { if (!isImageWindowOpen()) { // stop live acquistion if the window is not open if (IsLiveModeOn()) { enableLiveMode(false); return true; // nothing to do } } core_.snapImage(); Object img; img = core_.getImage(); if (imageWin_.windowNeedsResizing()) { createImageWindow(); } if (!isCurrentImageFormatSupported()) { return false; } imageWin_.newImage(img); updateLineProfile(); } catch (Exception e) { ReportingUtils.showError(e); return false; } return true; } public boolean displayImage(Object pixels) { try { if (!isImageWindowOpen() || imageWin_.windowNeedsResizing() // || imageWin_.getImageWindowByteLength() // != imageWin_.imageByteLenth(pixels) && creatingImageWindow_.isFalse()) { createImageWindow(); } imageWin_.newImage(pixels); updateLineProfile(); } catch (Exception e) { ReportingUtils.logError(e); return false; } return true; } public boolean displayImageWithStatusLine(Object pixels, String statusLine) { try { if (!isImageWindowOpen() || imageWin_.windowNeedsResizing() // imageWin_.getImageWindowByteLength() // != imageWin_.imageByteLenth(pixels) && creatingImageWindow_.isFalse()) { createImageWindow(); } imageWin_.newImageWithStatusLine(pixels, statusLine); updateLineProfile(); } catch (Exception e) { ReportingUtils.logError(e); return false; } return true; } public void displayStatusLine(String statusLine) { try { if (isImageWindowOpen()) { imageWin_.displayStatusLine(statusLine); } } catch (Exception e) { ReportingUtils.logError(e); return; } } private boolean isCurrentImageFormatSupported() { boolean ret = false; long channels = core_.getNumberOfComponents(); long bpp = core_.getBytesPerPixel(); if (channels > 1 && channels != 4 && bpp != 1) { handleError("Unsupported image format."); } else { ret = true; } return ret; } private void doSnap() { try { Cursor waitCursor = new Cursor(Cursor.WAIT_CURSOR); setCursor(waitCursor); if (!isImageWindowOpen()) { imageWin_ = createImageWindow(); } imageWin_.toFront(); setIJCal(imageWin_); // this is needed to clear the subtite, should be folded into // drawInfo imageWin_.getGraphics().clearRect(0, 0, imageWin_.getWidth(), 40); imageWin_.drawInfo(imageWin_.getGraphics()); imageWin_.setSubTitle("Snap"); String expStr = textFieldExp_.getText(); if (expStr.length() > 0) { core_.setExposure(NumberUtils.displayStringToDouble(expStr)); updateImage(); } else { handleError("Exposure field is empty!"); } } catch (Exception e) { ReportingUtils.showError(e); } Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); setCursor(defaultCursor); } public void initializeGUI() { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); engine_.setZStageDevice(zStageLabel_); if (cameraLabel_.length() > 0) { ActionListener[] listeners; // binning combo if (comboBinning_.getItemCount() > 0) { comboBinning_.removeAllItems(); } StrVector binSizes = core_.getAllowedPropertyValues( cameraLabel_, MMCoreJ.getG_Keyword_Binning()); listeners = comboBinning_.getActionListeners(); for (int i = 0; i < listeners.length; i++) { comboBinning_.removeActionListener(listeners[i]); } for (int i = 0; i < binSizes.size(); i++) { comboBinning_.addItem(binSizes.get(i)); } comboBinning_.setMaximumRowCount((int) binSizes.size()); if (binSizes.size() == 0) { comboBinning_.setEditable(true); } else { comboBinning_.setEditable(false); } for (int i = 0; i < listeners.length; i++) { comboBinning_.addActionListener(listeners[i]); } } // active shutter combo try { shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice); } catch (Exception e) { // System.println(DeviceType.ShutterDevice); ReportingUtils.logError(e); } if (shutters_ != null) { String items[] = new String[(int) shutters_.size()]; // items[0] = ""; for (int i = 0; i < shutters_.size(); i++) { items[i] = shutters_.get(i); } GUIUtils.replaceComboContents(shutterComboBox_, items); String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // Autofocus buttonAutofocusTools_.setEnabled(afMgr_.getDevice() != null); buttonAutofocus_.setEnabled(afMgr_.getDevice() != null); // Rebuild stage list in XY PositinList if (posListDlg_ != null) { posListDlg_.rebuildAxisList(); } // Mouse moves stage centerAndDragListener_ = new CenterAndDragListener(core_, gui_); if (centerAndDragMenuItem_.isSelected()) { centerAndDragListener_.start(); } updateGUI(true); } catch (Exception e) { ReportingUtils.showError(e); } } public String getVersion() { return VERSION; } private void initializePluginMenu() { // add plugin menu items if (plugins_.size() > 0) { final JMenu pluginMenu = new JMenu(); pluginMenu.setText("Plugins"); menuBar_.add(pluginMenu); for (int i = 0; i < plugins_.size(); i++) { final JMenuItem newMenuItem = new JMenuItem(); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { ReportingUtils.logMessage("Plugin command: " + e.getActionCommand()); // find the coresponding plugin for (int i = 0; i < plugins_.size(); i++) { if (plugins_.get(i).menuItem.equals(e.getActionCommand())) { PluginItem plugin = plugins_.get(i); plugin.instantiate(); plugin.plugin.show(); break; } } // if (plugins_.get(i).plugin == null) { // hcsPlateEditor_ = new // PlateEditor(MMStudioMainFrame.this); // } // hcsPlateEditor_.setVisible(true); } }); newMenuItem.setText(plugins_.get(i).menuItem); pluginMenu.add(newMenuItem); } } // add help menu item final JMenu helpMenu = new JMenu(); helpMenu.setText("Help"); menuBar_.add(helpMenu); final JMenuItem usersGuideMenuItem = new JMenuItem(); usersGuideMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Userguide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); usersGuideMenuItem.setText("User's Guide..."); helpMenu.add(usersGuideMenuItem); final JMenuItem configGuideMenuItem = new JMenuItem(); configGuideMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ij.plugin.BrowserLauncher.openURL("http://micro-manager.org/documentation.php?object=Configguide"); } catch (IOException e1) { ReportingUtils.showError(e1); } } }); configGuideMenuItem.setText("Configuration Guide..."); helpMenu.add(configGuideMenuItem); if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) { final JMenuItem registerMenuItem = new JMenuItem(); registerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_); regDlg.setVisible(true); } catch (Exception e1) { ReportingUtils.showError(e1); } } }); registerMenuItem.setText("Register your copy of Micro-Manager..."); helpMenu.add(registerMenuItem); } final JMenuItem aboutMenuItem = new JMenuItem(); aboutMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MMAboutDlg dlg = new MMAboutDlg(); String versionInfo = "MM Studio version: " + VERSION; versionInfo += "\n" + core_.getVersionInfo(); versionInfo += "\n" + core_.getAPIVersionInfo(); versionInfo += "\nUser: " + core_.getUserId(); versionInfo += "\nHost: " + core_.getHostName(); dlg.setVersionInfo(versionInfo); dlg.setVisible(true); } }); aboutMenuItem.setText("About..."); helpMenu.add(aboutMenuItem); } public void updateGUI(boolean updateConfigPadStructure) { try { // establish device roles cameraLabel_ = core_.getCameraDevice(); shutterLabel_ = core_.getShutterDevice(); zStageLabel_ = core_.getFocusDevice(); xyStageLabel_ = core_.getXYStageDevice(); afMgr_.refresh(); // camera settings if (isCameraAvailable()) { double exp = core_.getExposure(); textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp)); String binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning()); GUIUtils.setComboSelection(comboBinning_, binSize); long bitDepth = 8; if (imageWin_ != null) { long hsz = imageWin_.getRawHistogramSize(); bitDepth = (long) Math.log(hsz); } bitDepth = core_.getImageBitDepth(); contrastPanel_.setPixelBitDepth((int) bitDepth, false); } if (!liveModeTimer_.isRunning()) { autoShutterCheckBox_.setSelected(core_.getAutoShutter()); boolean shutterOpen = core_.getShutterOpen(); setShutterButton(shutterOpen); if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } autoShutterOrg_ = core_.getAutoShutter(); } // active shutter combo if (shutters_ != null) { String activeShutter = core_.getShutterDevice(); if (activeShutter != null) { shutterComboBox_.setSelectedItem(activeShutter); } else { shutterComboBox_.setSelectedItem(""); } } // state devices if (updateConfigPadStructure && (configPad_ != null)) { configPad_.refreshStructure(); } // update Channel menus in Multi-dimensional acquisition dialog updateChannelCombos(); } catch (Exception e) { ReportingUtils.logError(e); } updateStaticInfo(); updateTitle(); } public boolean okToAcquire() { return !liveModeTimer_.isRunning(); } public void stopAllActivity() { enableLiveMode(false); } public void refreshImage() { if (imageWin_ != null) { imageWin_.getImagePlus().updateAndDraw(); } } private void cleanupOnClose() { // NS: Save config presets if they were changed. if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } } liveModeTimer_.stop(); try{ if (imageWin_ != null) { if (!imageWin_.isClosed()) imageWin_.close(); imageWin_.dispose(); imageWin_ = null; } } catch( Throwable t){ ReportingUtils.logError(t, "closing ImageWin_"); } if (profileWin_ != null) { removeMMBackgroundListener(profileWin_); profileWin_.dispose(); } if (scriptPanel_ != null) { removeMMBackgroundListener(scriptPanel_); scriptPanel_.closePanel(); } if (propertyBrowser_ != null) { removeMMBackgroundListener(propertyBrowser_); propertyBrowser_.dispose(); } if (acqControlWin_ != null) { removeMMBackgroundListener(acqControlWin_); acqControlWin_.close(); } if (engine_ != null) { engine_.shutdown(); } if (afMgr_ != null) { afMgr_.closeOptionsDialog(); } // dispose plugins for (int i = 0; i < plugins_.size(); i++) { MMPlugin plugin = (MMPlugin) plugins_.get(i).plugin; if (plugin != null) { plugin.dispose(); } } try { core_.reset(); } catch (Exception err) { ReportingUtils.showError(err); } } private void saveSettings() { Rectangle r = this.getBounds(); mainPrefs_.putInt(MAIN_FRAME_X, r.x); mainPrefs_.putInt(MAIN_FRAME_Y, r.y); mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width); mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height); mainPrefs_.putBoolean(MAIN_STRETCH_CONTRAST, contrastPanel_.isContrastStretch()); mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_); // save field values from the main window // NOTE: automatically restoring these values on startup may cause // problems mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText()); // NOTE: do not save auto shutter state // mainPrefs_.putBoolean(MAIN_AUTO_SHUTTER, // autoShutterCheckBox_.isSelected()); if (afMgr_.getDevice() != null) { mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName()); } } private void loadConfiguration() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysConfigFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysConfigFile_ = f.getAbsolutePath(); configChanged_ = false; setConfigSaveButtonStatus(configChanged_); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); } } private void loadSystemState() { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new CfgFileFilter()); fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); sysStateFile_ = f.getAbsolutePath(); try { // WaitDialog waitDlg = new // WaitDialog("Loading saved state, please wait..."); // waitDlg.showDialog(); core_.loadSystemState(sysStateFile_); GUIUtils.preventDisplayAdapterChangeExceptions(); // waitDlg.closeDialog(); initializeGUI(); } catch (Exception e) { ReportingUtils.showError(e); return; } } } private void saveSystemState() { JFileChooser fc = new JFileChooser(); boolean saveFile = true; File f; do { fc.setSelectedFile(new File(sysStateFile_)); int retVal = fc.showSaveDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { f = fc.getSelectedFile(); // check if file already exists if (f.exists()) { int sel = JOptionPane.showConfirmDialog(this, "Overwrite " + f.getName(), "File Save", JOptionPane.YES_NO_OPTION); if (sel == JOptionPane.YES_OPTION) { saveFile = true; } else { saveFile = false; } } } else { return; } } while (saveFile == false); sysStateFile_ = f.getAbsolutePath(); try { core_.saveSystemState(sysStateFile_); } catch (Exception e) { ReportingUtils.showError(e); return; } } public void closeSequence() { if (engine_ != null && engine_.isAcquisitionRunning()) { int result = JOptionPane.showConfirmDialog( this, "Acquisition in progress. Are you sure you want to exit and discard all data?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result == JOptionPane.NO_OPTION) { return; } } stopAllActivity(); cleanupOnClose(); saveSettings(); configPad_.saveSettings(); options_.saveSettings(); dispose(); if (!runsAsPlugin_) { System.exit(0); } else { ImageJ ij = IJ.getInstance(); if (ij != null) { ij.quit(); } } } public void applyContrastSettings(ContrastSettings contrast8, ContrastSettings contrast16) { contrastPanel_.applyContrastSettings(contrast8, contrast16); } public ContrastSettings getContrastSettings() { return contrastPanel_.getContrastSettings(); } public boolean is16bit() { if (isImageWindowOpen() && imageWin_.getImagePlus().getProcessor() instanceof ShortProcessor) { return true; } return false; } public boolean isRunning() { return running_; } /** * Executes the beanShell script. This script instance only supports * commands directed to the core object. */ private void executeStartupScript() { // execute startup script File f = new File(startupScriptFile_); if (startupScriptFile_.length() > 0 && f.exists()) { WaitDialog waitDlg = new WaitDialog( "Executing startup script, please wait..."); waitDlg.showDialog(); Interpreter interp = new Interpreter(); try { // insert core object only interp.set(SCRIPT_CORE_OBJECT, core_); interp.set(SCRIPT_ACQENG_OBJECT, engine_); interp.set(SCRIPT_GUI_OBJECT, this); // read text file and evaluate interp.eval(TextUtils.readTextFile(startupScriptFile_)); } catch (IOException exc) { ReportingUtils.showError(exc, "Unable to read the startup script (" + startupScriptFile_ + ")."); } catch (EvalError exc) { ReportingUtils.showError(exc); } finally { waitDlg.closeDialog(); } } else { if (startupScriptFile_.length() > 0) ReportingUtils.logMessage("Startup script file ("+startupScriptFile_+") not present."); } } /** * Loads sytem configuration from the cfg file. */ private boolean loadSystemConfiguration() { boolean result = true; saveMRUConfigFiles(); final WaitDialog waitDlg = new WaitDialog( "Loading system configuration, please wait..."); waitDlg.setAlwaysOnTop(true); waitDlg.showDialog(); this.setEnabled(false); try { if (sysConfigFile_.length() > 0) { GUIUtils.preventDisplayAdapterChangeExceptions(); core_.waitForSystem(); core_.loadSystemConfiguration(sysConfigFile_); GUIUtils.preventDisplayAdapterChangeExceptions(); waitDlg.closeDialog(); } else { waitDlg.closeDialog(); } } catch (final Exception err) { GUIUtils.preventDisplayAdapterChangeExceptions(); waitDlg.closeDialog(); ReportingUtils.showError(err); result = false; } this.setEnabled(true); this.initializeGUI(); updateSwitchConfigurationMenu(); return result; } private void saveMRUConfigFiles() { if (0 < sysConfigFile_.length()) { if (MRUConfigFiles_.contains(sysConfigFile_)) { MRUConfigFiles_.remove(sysConfigFile_); } if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); // save the MRU list to the preferences for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) { String value = ""; if (null != MRUConfigFiles_.get(icfg)) { value = MRUConfigFiles_.get(icfg).toString(); } mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value); } } } private void loadMRUConfigFiles() { sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_); // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE, // startupScriptFile_); MRUConfigFiles_ = new ArrayList<String>(); for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) { String value = ""; value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value); if (0 < value.length()) { File ruFile = new File(value); if (ruFile.exists()) { if (!MRUConfigFiles_.contains(value)) { MRUConfigFiles_.add(value); } } } } // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE if (0 < sysConfigFile_.length()) { if (!MRUConfigFiles_.contains(sysConfigFile_)) { // in case persistant data is inconsistent if (maxMRUCfgs_ <= MRUConfigFiles_.size()) { MRUConfigFiles_.remove(maxMRUCfgs_ - 1); } MRUConfigFiles_.add(0, sysConfigFile_); } } } /** * Opens Acquisition dialog. */ private void openAcqControlDialog() { try { if (acqControlWin_ == null) { acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this); } if (acqControlWin_.isActive()) { acqControlWin_.setTopPosition(); } acqControlWin_.setVisible(true); // TODO: this call causes a strange exception the first time the // dialog is created // something to do with the order in which combo box creation is // performed // acqControlWin_.updateGroupsCombo(); } catch (Exception exc) { ReportingUtils.showError(exc, "\nAcquistion window failed to open due to invalid or corrupted settings.\n" + "Try resetting registry settings to factory defaults (Menu Tools|Options)."); } } /** * Opens streaming sequence acquisition dialog. */ protected void openSequenceDialog() { try { if (fastAcqWin_ == null) { fastAcqWin_ = new FastAcqDlg(core_, this); } fastAcqWin_.setVisible(true); } catch (Exception exc) { ReportingUtils.showError(exc, "\nSequence window failed to open due to internal error."); } } /** * Opens Split View dialog. */ protected void splitViewDialog() { try { if (splitView_ == null) { splitView_ = new SplitView(core_, this, options_); } splitView_.setVisible(true); } catch (Exception exc) { ReportingUtils.showError(exc, "\nSplit View Window failed to open due to internal error."); } } /** * /** Opens a dialog to record stage positions */ public void showXYPositionList() { if (posListDlg_ == null) { posListDlg_ = new PositionListDlg(core_, this, posList_, options_); } posListDlg_.setVisible(true); } private void updateChannelCombos() { if (this.acqControlWin_ != null) { this.acqControlWin_.updateChannelAndGroupCombo(); } } public void setConfigChanged(boolean status) { configChanged_ = status; setConfigSaveButtonStatus(configChanged_); } /** * Returns the current background color * @return */ public Color getBackgroundColor() { return guiColors_.background.get((options_.displayBackground)); } /* * Changes background color of this window and all other MM windows */ public void setBackgroundStyle(String backgroundType) { setBackground(guiColors_.background.get((options_.displayBackground))); paint(MMStudioMainFrame.this.getGraphics()); // sets background of all registered Components for (Component comp:MMFrames_) { if (comp != null) comp.setBackground(guiColors_.background.get((options_.displayBackground))); } } public String getBackgroundStyle() { return options_.displayBackground; } // Set ImageJ pixel calibration private void setIJCal(MMImageWindow imageWin) { if (imageWin != null) { imageWin.setIJCal(); } } // ////////////////////////////////////////////////////////////////////////// // Scripting interface // ////////////////////////////////////////////////////////////////////////// private class ExecuteAcq implements Runnable { public ExecuteAcq() { } public void run() { if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); } } } private class LoadAcq implements Runnable { private String filePath_; public LoadAcq(String path) { filePath_ = path; } public void run() { // stop current acquisition if any engine_.shutdown(); // load protocol if (acqControlWin_ != null) { acqControlWin_.loadAcqSettingsFromFile(filePath_); } } } private class RefreshPositionList implements Runnable { public RefreshPositionList() { } public void run() { if (posListDlg_ != null) { posListDlg_.setPositionList(posList_); engine_.setPositionList(posList_); } } } private void testForAbortRequests() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } } } public void startBurstAcquisition() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ != null) { fastAcqWin_.start(); } } public void runBurstAcquisition() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ == null) { fastAcqWin_ = new FastAcqDlg(core_, this); addMMBackgroundListener(fastAcqWin_); } fastAcqWin_.setVisible(true); fastAcqWin_.start(); try { while (fastAcqWin_.isBusy()) { Thread.sleep(20); } } catch (InterruptedException e) { ReportingUtils.showError(e); } } public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException { if (fastAcqWin_ == null) { fastAcqWin_ = new FastAcqDlg(core_, this); } fastAcqWin_.setSequenceLength(nr); fastAcqWin_.setDirRoot(root); fastAcqWin_.setName(name); runBurstAcquisition(); } public void runBurstAcquisition(int nr) throws MMScriptException { if (fastAcqWin_ == null) { fastAcqWin_ = new FastAcqDlg(core_, this); } fastAcqWin_.setSequenceLength(nr); runBurstAcquisition(); } public boolean isBurstAcquisitionRunning() throws MMScriptException { testForAbortRequests(); if (fastAcqWin_ != null) { return fastAcqWin_.isBusy(); } else { return false; } } public void startAcquisition() throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new ExecuteAcq()); } public void runAcquisition() throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(50); } } catch (InterruptedException e) { ReportingUtils.showError(e); } } else { throw new MMScriptException( "Acquisition window must be open for this command to work."); } } public void runAcquisition(String name, String root) throws MMScriptException { testForAbortRequests(); if (acqControlWin_ != null) { acqControlWin_.runAcquisition(name, root); try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(100); } } catch (InterruptedException e) { ReportingUtils.showError(e); } } else { throw new MMScriptException( "Acquisition window must be open for this command to work."); } } public void runAcqusition(String name, String root) throws MMScriptException { runAcquisition(name, root); } public void loadAcquisition(String path) throws MMScriptException { testForAbortRequests(); SwingUtilities.invokeLater(new LoadAcq(path)); } public void setPositionList(PositionList pl) throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object posList_ = PositionList.newInstance(pl); SwingUtilities.invokeLater(new RefreshPositionList()); } public PositionList getPositionList() throws MMScriptException { testForAbortRequests(); // use serialization to clone the PositionList object return PositionList.newInstance(posList_); } public void sleep(long ms) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.sleep(ms); } } public void openAcquisition(String name, String rootDir) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir); AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices) throws MMScriptException { openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, int nrPositions, boolean show, boolean virtual) throws MMScriptException { acqMgr_.openAcquisition(name, rootDir, show, virtual); AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions); } public void openAcquisition(String name, String rootDir, int nrFrames, int nrChannels, int nrSlices, boolean show, boolean virtual) throws MMScriptException { this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual); } private void openAcquisitionSnap(String name, String rootDir, boolean show) throws MMScriptException { AcquisitionInterface acq = acqMgr_.openAcquisitionSnap(name, rootDir, this, show); acq.setDimensions(0, 1, 1, 1); try { // acq.getAcqData().setPixelSizeUm(core_.getPixelSizeUm()); acq.setProperty(SummaryKeys.IMAGE_PIXEL_SIZE_UM, String.valueOf(core_.getPixelSizeUm())); } catch (Exception e) { ReportingUtils.showError(e); } } public void initializeAcquisition(String name, int width, int height, int depth) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.setImagePhysicalDimensions(width, height, depth); acq.initialize(); } public Boolean acquisitionExists(String name) { return acqMgr_.acquisitionExists(name); } public void closeAcquisition(String name) throws MMScriptException { acqMgr_.closeAcquisition(name); } public void closeAcquisitionImage5D(String title) throws MMScriptException { acqMgr_.closeImage5D(title); } public void loadBurstAcquisition(String path) { // TODO Auto-generated method stub } public void refreshGUI() { updateGUI(true); } public void setAcquisitionProperty(String acqName, String propertyName, String value) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); acq.setProperty(propertyName, value); } public void setAcquisitionSystemState(String acqName, Map<String,String> md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSystemState(md); } public void setAcquisitionSummary(String acqName, Map<String,String> md) throws MMScriptException { acqMgr_.getAcquisition(acqName).setSummaryProperties(md); } public void setImageProperty(String acqName, int frame, int channel, int slice, String propName, String value) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(acqName); acq.setProperty(frame, channel, slice, propName, value); } public void snapAndAddImage(String name, int frame, int channel, int slice) throws MMScriptException { Metadata md = new Metadata(); try { Object img; if (core_.isSequenceRunning()) { img = core_.getLastImage(); core_.getLastImageMD(0, 0, md); } else { core_.snapImage(); img = core_.getImage(); } AcquisitionInterface acq = acqMgr_.getAcquisition(name); long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); if (!acq.isInitialized()) { acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth); acq.initialize(); } acq.insertImage(img, frame, channel, slice); // Insert exposure in metadata acq.setProperty(frame, channel, slice, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure())); // Add pixel size calibration double pixSizeUm = core_.getPixelSizeUm(); if (pixSizeUm > 0) { acq.setProperty(frame, channel, slice, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); acq.setProperty(frame, channel, slice, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); } // generate list with system state JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache()); // and insert into metadata acq.setSystemState(frame, channel, slice, state); } catch (Exception e) { ReportingUtils.showError(e); } } public void addToSnapSeries(Object img, String acqName) { try { // boolean liveRunning = liveRunning_; // if (liveRunning) // enableLiveMode(false); if (acqName == null) { acqName = "Snap" + snapCount_; } Boolean newSnap = false; core_.setExposure(NumberUtils.displayStringToDouble(textFieldExp_.getText())); long width = core_.getImageWidth(); long height = core_.getImageHeight(); long depth = core_.getBytesPerPixel(); MMAcquisitionSnap acq = null; if (acqMgr_.hasActiveImage5D(acqName)) { acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName); newSnap = !acq.isCompatibleWithCameraSettings(); } else { newSnap = true; } if (newSnap) { snapCount_++; acqName = "Snap" + snapCount_; this.openAcquisitionSnap(acqName, null, true); // (dir=null) -> // keep in // memory; don't // save to file. initializeAcquisition(acqName, (int) width, (int) height, (int) depth); } setChannelColor(acqName, 0, Color.WHITE); setChannelName(acqName, 0, "Snap"); acq = (MMAcquisitionSnap) acqMgr_.getAcquisition(acqName); acq.appendImage(img); // add exposure to metadata acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.EXPOSURE_MS, NumberUtils.doubleToDisplayString(core_.getExposure())); // Add pixel size calibration double pixSizeUm = core_.getPixelSizeUm(); if (pixSizeUm > 0) { acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.X_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); acq.setProperty(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, ImagePropertyKeys.Y_UM, NumberUtils.doubleToDisplayString(pixSizeUm)); } // generate list with system state JSONObject state = Annotator.generateJSONMetadata(core_.getSystemStateCache()); // and insert into metadata acq.setSystemState(acq.getFrames() - 1, acq.getChannels() - 1, acq.getSlices() - 1, state); // if (liveRunning) // enableLiveMode(true); // closeAcquisition(acqName); } catch (Exception e) { ReportingUtils.showError(e); } } public void addImage(String name, Object img, int frame, int channel, int slice) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(name); acq.insertImage(img, frame, channel, slice); } public void addImage(String name, TaggedImage taggedImg) throws MMScriptException { acqMgr_.getAcquisition(name).insertImage(taggedImg); } public void closeAllAcquisitions() { acqMgr_.closeAll(); } private class ScriptConsoleMessage implements Runnable { String msg_; public ScriptConsoleMessage(String text) { msg_ = text; } public void run() { scriptPanel_.message(msg_); } } public void message(String text) throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } SwingUtilities.invokeLater(new ScriptConsoleMessage(text)); } } public void clearMessageWindow() throws MMScriptException { if (scriptPanel_ != null) { if (scriptPanel_.stopRequestPending()) { throw new MMScriptException("Script interrupted by the user!"); } scriptPanel_.clearOutput(); } } public void clearOutput() throws MMScriptException { clearMessageWindow(); } public void clear() throws MMScriptException { clearMessageWindow(); } public void setChannelContrast(String title, int channel, int min, int max) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelContrast(channel, min, max); } public void setChannelName(String title, int channel, String name) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelName(channel, name); } public void setChannelColor(String title, int channel, Color color) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setChannelColor(channel, color.getRGB()); } public void setContrastBasedOnFrame(String title, int frame, int slice) throws MMScriptException { AcquisitionInterface acq = acqMgr_.getAcquisition(title); acq.setContrastBasedOnFrame(frame, slice); } public boolean runWellScan(WellAcquisitionData wad) throws MMScriptException { System.out.println("Inside MMStudioMainFrame -- Run Well Scan"); boolean result = true; testForAbortRequests(); if (acqControlWin_ == null) { openAcqControlDialog(); } engine_.setPositionList(posList_); result = acqControlWin_.runWellScan(wad); if (result == false) { return result; //throw new MMScriptException("Scanning error."); } try { while (acqControlWin_.isAcquisitionRunning()) { Thread.sleep(500); } } catch (InterruptedException e) { ReportingUtils.showError(e); result = false; return result; } return result; } public void setStagePosition(double z) throws MMScriptException { try { core_.setPosition(core_.getFocusDevice(),z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeStagePosition(double z) throws MMScriptException { try { cb_.onStagePositionChangedRelative(core_.getFocusDevice(), z); core_.setRelativePosition(core_.getFocusDevice(), z); core_.waitForDevice(core_.getFocusDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setXYStagePosition(double x, double y) throws MMScriptException { try { core_.setXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public void setRelativeXYStagePosition(double x, double y) throws MMScriptException { try { cb_.onXYStagePositionChangedRelative(core_.getXYStageDevice(), x, y); core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y); core_.waitForDevice(core_.getXYStageDevice()); } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public Point2D.Double getXYStagePosition() throws MMScriptException { String stage = core_.getXYStageDevice(); if (stage.length() == 0) { throw new MMScriptException("XY Stage device is not available"); } double x[] = new double[1]; double y[] = new double[1]; try { core_.getXYPosition(stage, x, y); Point2D.Double pt = new Point2D.Double(x[0], y[0]); return pt; } catch (Exception e) { throw new MMScriptException(e.getMessage()); } } public String getXYStageName() { return core_.getXYStageDevice(); } public void setXYOrigin(double x, double y) throws MMScriptException { String xyStage = core_.getXYStageDevice(); try { core_.setAdapterOriginXY(xyStage, x, y); } catch (Exception e) { throw new MMScriptException(e); } } public AcquisitionEngine getAcquisitionEngine() { return engine_; } public String installPlugin(Class<?> cl) { String className = cl.getSimpleName(); String msg = new String(className + " module loaded."); try { for (PluginItem plugin : plugins_) { if (plugin.className.contentEquals(className)) { return className + " already loaded."; } } PluginItem pi = new PluginItem(); pi.className = className; try { // Get this static field from the class implementing MMPlugin. pi.menuItem = (String) cl.getDeclaredField("menuName").get(null); } catch (SecurityException e) { ReportingUtils.logError(e); pi.menuItem = className; } catch (NoSuchFieldException e) { pi.menuItem = className; ReportingUtils.logError(className + " fails to implement static String menuName."); } catch (IllegalArgumentException e) { ReportingUtils.logError(e); } catch (IllegalAccessException e) { ReportingUtils.logError(e); } if (pi.menuItem == null) { pi.menuItem = className; //core_.logMessage(className + " fails to implement static String menuName."); } pi.pluginClass = cl; plugins_.add(pi); } catch (NoClassDefFoundError e) { msg = className + " class definition not found."; ReportingUtils.logError(e, msg); } return msg; } public String installPlugin(String className, String menuName) { String msg = "installPlugin(String className, String menuName) is deprecated. Use installPlugin(String className) instead."; core_.logMessage(msg); installPlugin(className); return msg; } public String installPlugin(String className) { String msg = ""; try { return installPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { msg = className + " plugin not found."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(String className) { try { return installAutofocusPlugin(Class.forName(className)); } catch (ClassNotFoundException e) { String msg = "Internal error: AF manager not instantiated."; ReportingUtils.logError(e, msg); return msg; } } public String installAutofocusPlugin(Class<?> autofocus) { String msg = new String(autofocus.getSimpleName() + " module loaded."); if (afMgr_ != null) { try { afMgr_.refresh(); } catch (MMException e) { msg = e.getMessage(); ReportingUtils.logError(e); } afMgr_.setAFPluginClassName(autofocus.getSimpleName()); } else { msg = "Internal error: AF manager not instantiated."; } return msg; } public CMMCore getCore() { return core_; } public void snapAndAddToImage5D(String acqName) { Object img; try { boolean liveRunning = liveRunning_; if (liveRunning) { img = core_.getLastImage(); } else { core_.snapImage(); img = core_.getImage(); } addToSnapSeries(img, acqName); } catch (Exception e) { ReportingUtils.showError(e); } } //Returns true if there is a newer image to display that can be get from MMCore //Implements "optimistic" approach: returns true even //if there was an error while getting the image time stamp private boolean isNewImageAvailable() { boolean ret = true; /* disabled until metadata-related methods in MMCoreJ can handle exceptions Metadata md = new Metadata(); MetadataSingleTag tag = null; try { core_.getLastImageMD(0, 0, md); String strTag=MMCoreJ.getG_Keyword_Elapsed_Time_ms(); tag = md.GetSingleTag(strTag); if(tag != null) { double newFrameTimeStamp = Double.valueOf(tag.GetValue()); ret = newFrameTimeStamp > lastImageTimeMs_; if (ret) { lastImageTimeMs_ = newFrameTimeStamp; } } } catch(Exception e) { ReportingUtils.logError(e); } */ return ret; } ; public void suspendLiveMode() { liveModeSuspended_ = IsLiveModeOn(); enableLiveMode(false); } public void resumeLiveMode() { if (liveModeSuspended_) { enableLiveMode(true); } } public Autofocus getAutofocus() { return afMgr_.getDevice(); } public void showAutofocusDialog() { if (afMgr_.getDevice() != null) { afMgr_.showOptionsDialog(); } } public AutofocusManager getAutofocusManager() { return afMgr_; } public void selectConfigGroup(String groupName) { configPad_.setGroup(groupName); } private void loadPlugins() { ArrayList<Class<?>> pluginClasses = new ArrayList<Class<?>>(); ArrayList<Class<?>> autofocusClasses = new ArrayList<Class<?>>(); List<Class<?>> classes; try { classes = JavaUtils.findClasses(new File("mmplugins"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == MMPlugin.class) { pluginClasses.add(clazz); } } } classes = JavaUtils.findClasses(new File("mmautofocus"), 2); for (Class<?> clazz : classes) { for (Class<?> iface : clazz.getInterfaces()) { //core_.logMessage("interface found: " + iface.getName()); if (iface == Autofocus.class) { autofocusClasses.add(clazz); } } } } catch (ClassNotFoundException e1) { ReportingUtils.logError(e1); } for (Class<?> plugin : pluginClasses) { try { installPlugin(plugin); } catch (Exception e) { ReportingUtils.logError(e, "Attempted to install the \"" + plugin.getName() + "\" plugin ."); } } for (Class<?> autofocus : autofocusClasses) { try { installAutofocusPlugin(autofocus.getName()); } catch (Exception e) { ReportingUtils.logError("Attempted to install the \"" + autofocus.getName() + "\" autofocus plugin."); } } } /** * */ private void setLiveModeInterval() { double interval = 33.0; try { if (core_.getExposure() > 33.0) { interval = core_.getExposure(); } } catch (Exception ex) { ReportingUtils.showError(ex); } liveModeInterval_ = interval; liveModeTimer_.setDelay((int) liveModeInterval_); liveModeTimer_.setInitialDelay(liveModeTimer_.getDelay()); } public void logMessage(String msg) { ReportingUtils.logMessage(msg); } public void showMessage(String msg) { ReportingUtils.showMessage(msg); } public void logError(Exception e, String msg) { ReportingUtils.logError(e, msg); } public void logError(Exception e) { ReportingUtils.logError(e); } public void logError(String msg) { ReportingUtils.logError(msg); } public void showError(Exception e, String msg) { ReportingUtils.showError(e, msg); } public void showError(Exception e) { ReportingUtils.showError(e); } public void showError(String msg) { ReportingUtils.showError(msg); } } class BooleanLock extends Object { private boolean value; public BooleanLock(boolean initialValue) { value = initialValue; } public BooleanLock() { this(false); } public synchronized void setValue(boolean newValue) { if (newValue != value) { value = newValue; notifyAll(); } } public synchronized boolean waitToSetTrue(long msTimeout) throws InterruptedException { boolean success = waitUntilFalse(msTimeout); if (success) { setValue(true); } return success; } public synchronized boolean waitToSetFalse(long msTimeout) throws InterruptedException { boolean success = waitUntilTrue(msTimeout); if (success) { setValue(false); } return success; } public synchronized boolean isTrue() { return value; } public synchronized boolean isFalse() { return !value; } public synchronized boolean waitUntilTrue(long msTimeout) throws InterruptedException { return waitUntilStateIs(true, msTimeout); } public synchronized boolean waitUntilFalse(long msTimeout) throws InterruptedException { return waitUntilStateIs(false, msTimeout); } public synchronized boolean waitUntilStateIs( boolean state, long msTimeout) throws InterruptedException { if (msTimeout == 0L) { while (value != state) { wait(); } return true; } long endTime = System.currentTimeMillis() + msTimeout; long msRemaining = msTimeout; while ((value != state) && (msRemaining > 0L)) { wait(msRemaining); msRemaining = endTime - System.currentTimeMillis(); } return (value == state); } }
true
true
public MMStudioMainFrame(boolean pluginStatus) { super(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { ReportingUtils.showError(e, "An uncaught exception was thrown in thread " + t.getName() + "."); } }); options_ = new MMOptions(); options_.loadSettings(); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; // !!! contrastSettings8_ = new ContrastSettings(); // contrastSettings16_ = new ContrastSettings(); acqMgr_ = new AcquisitionManager(); sysConfigFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME); if (options_.startupScript.length() > 0) { startupScriptFile_ = new String(System.getProperty("user.dir") + "/" + options_.startupScript); } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); systemPrefs_ = mainPrefs_; // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } // initialize timer ActionListener liveModeTimerHandler = new ActionListener() { public void actionPerformed(ActionEvent evt) { if (!isImageWindowOpen()) { // stop live acquisition if user closed the window enableLiveMode(false); return; } if (!isNewImageAvailable()) { return; } try { Object img; if (!liveModeFullyStarted_) { if (core_.getRemainingImageCount() > 0) { liveModeFullyStarted_ = true; } } if (liveModeFullyStarted_) { img = core_.getLastImage(); if (img != img_) { img_ = img; displayImage(img_); } } } catch (Exception e) { ReportingUtils.showError(e); return; } } }; liveModeTimer_ = new Timer((int) liveModeInterval_, liveModeTimerHandler); liveModeTimer_.stop(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 451); boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); setBounds(x, y, width, height); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); springLayout_ = new SpringLayout(); getContentPane().setLayout(springLayout_); setTitle(MICRO_MANAGER_TITLE); setBackground(guiColors_.background.get((options_.displayBackground))); // Snap button // ----------- buttonSnap_ = new JButton(); buttonSnap_.setIconTextGap(6); buttonSnap_.setText("Snap"); buttonSnap_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonSnap_.setToolTipText("Snap single image"); buttonSnap_.setMaximumSize(new Dimension(0, 0)); buttonSnap_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); getContentPane().add(buttonSnap_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap_, 4, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonSnap_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonSnap_, 7, SpringLayout.WEST, getContentPane()); // Initialize // ---------- // Exposure field // --------------- final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); getContentPane().add(label_1); springLayout_.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, getContentPane()); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { setExposure(); } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExposure(); } }); getContentPane().add(textFieldExp_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 276, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, getContentPane()); // Live button // ----------- toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2)); toggleButtonLive_.setIconTextGap(1); toggleButtonLive_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuous live view"); toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!IsLiveModeOn()) { // Display interval for Live Mode changes as well setLiveModeInterval(); } enableLiveMode(!IsLiveModeOn()); } }); toggleButtonLive_.setText("Live"); getContentPane().add(toggleButtonLive_); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, getContentPane()); // Acquire button // ----------- JButton acquireButton = new JButton(); acquireButton.setMargin(new Insets(2, 2, 2, 2)); acquireButton.setIconTextGap(1); acquireButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/snapAppend.png")); acquireButton.setIconTextGap(6); acquireButton.setToolTipText("Acquire single frame"); acquireButton.setFont(new Font("Arial", Font.PLAIN, 10)); acquireButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { snapAndAddToImage5D(null); } }); acquireButton.setText("Acquire"); getContentPane().add(acquireButton); springLayout_.putConstraint(SpringLayout.SOUTH, acquireButton, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, acquireButton, 48, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, acquireButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, acquireButton, 7, SpringLayout.WEST, getContentPane()); // Shutter button // -------------- toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { if (toggleButtonShutter_.isSelected()) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); getContentPane().add(toggleButtonShutter_); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138 - 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117 - 21, SpringLayout.NORTH, getContentPane()); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); getContentPane().add(activeShutterLabel); springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel, 160 - 2, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel, 113 - 2, SpringLayout.WEST, getContentPane()); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } return; } }); getContentPane().add(shutterComboBox_); springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, getContentPane()); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(); } }.start(); } }); openMenuItem.setText("Open Acquisition Data..."); fileMenu.add(openMenuItem); fileMenu.addSeparator(); final JMenuItem loadState = new JMenuItem(); loadState.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystemState(); } }); loadState.setText("Load System State..."); fileMenu.add(loadState); final JMenuItem saveStateAs = new JMenuItem(); fileMenu.add(saveStateAs); saveStateAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystemState(); } }); saveStateAs.setText("Save System State As..."); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); final JMenu image5dMenu = new JMenu(); image5dMenu.setText("Image5D"); menuBar_.add(image5dMenu); final JMenuItem closeAllMenuItem = new JMenuItem(); closeAllMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { WindowManager.closeAllWindows(); } }); closeAllMenuItem.setText("Close All"); image5dMenu.add(closeAllMenuItem); final JMenuItem duplicateMenuItem = new JMenuItem(); duplicateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Duplicate_Image5D duplicate = new Duplicate_Image5D(); duplicate.run(""); } }); duplicateMenuItem.setText("Duplicate"); image5dMenu.add(duplicateMenuItem); final JMenuItem cropMenuItem = new JMenuItem(); cropMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Crop_Image5D crop = new Crop_Image5D(); crop.run(""); } }); cropMenuItem.setText("Crop"); image5dMenu.add(cropMenuItem); final JMenuItem makeMontageMenuItem = new JMenuItem(); makeMontageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Make_Montage makeMontage = new Make_Montage(); makeMontage.run(""); } }); makeMontageMenuItem.setText("Make Montage"); image5dMenu.add(makeMontageMenuItem); final JMenuItem zProjectMenuItem = new JMenuItem(); zProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Z_Project projection = new Z_Project(); projection.run(""); } }); zProjectMenuItem.setText("Z Project"); image5dMenu.add(zProjectMenuItem); final JMenuItem convertToRgbMenuItem = new JMenuItem(); convertToRgbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB(); stackToRGB.run(""); } }); convertToRgbMenuItem.setText("Copy to RGB Stack(z)"); image5dMenu.add(convertToRgbMenuItem); final JMenuItem convertToRgbtMenuItem = new JMenuItem(); convertToRgbtMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t(); stackToRGB_t.run(""); } }); convertToRgbtMenuItem.setText("Copy to RGB Stack(t)"); image5dMenu.add(convertToRgbtMenuItem); final JMenuItem convertToStackMenuItem = new JMenuItem(); convertToStackMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_Stack image5DToStack = new Image5D_to_Stack(); image5DToStack.run(""); } }); convertToStackMenuItem.setText("Copy to Stack"); image5dMenu.add(convertToStackMenuItem); final JMenuItem convertToStacksMenuItem = new JMenuItem(); convertToStacksMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks(); image5DToStacks.run(""); } }); convertToStacksMenuItem.setText("Copy to Stacks (channels)"); image5dMenu.add(convertToStacksMenuItem); final JMenuItem volumeViewerMenuItem = new JMenuItem(); volumeViewerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer(); volumeViewer.run(""); } }); volumeViewerMenuItem.setText("VolumeViewer"); image5dMenu.add(volumeViewerMenuItem); final JMenuItem splitImageMenuItem = new JMenuItem(); splitImageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Split_Image5D splitImage = new Split_Image5D(); splitImage.run(""); } }); splitImageMenuItem.setText("SplitView"); image5dMenu.add(splitImageMenuItem); final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createScriptPanel(); } }); scriptPanelMenuItem.setText("Script Panel..."); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Multi-Dimensional Acquisition..."); toolsMenu.add(acquisitionMenuItem); final JMenuItem sequenceMenuItem = new JMenuItem(); sequenceMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); sequenceMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film_go.png")); sequenceMenuItem.setText("Burst Acquisition..."); toolsMenu.add(sequenceMenuItem); final JMenuItem splitViewMenuItem = new JMenuItem(); splitViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitViewDialog(); } }); splitViewMenuItem.setText("Split View..."); toolsMenu.add(splitViewMenuItem); centerAndDragMenuItem_ = new JCheckBoxMenuItem(); centerAndDragMenuItem_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (centerAndDragListener_ == null) { centerAndDragListener_ = new CenterAndDragListener(core_, gui_); } if (!centerAndDragListener_.isRunning()) { centerAndDragListener_.start(); centerAndDragMenuItem_.setSelected(true); } else { centerAndDragListener_.stop(); centerAndDragMenuItem_.setSelected(false); } mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }); centerAndDragMenuItem_.setText("Mouse Moves Stage"); centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); toolsMenu.add(centerAndDragMenuItem_); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_); configurator.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = configurator.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); } catch (Exception e) { ReportingUtils.showError(e); return; } } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadConfiguration(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); switchConfigurationMenu_ = new JMenu(); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Settings..."); toolsMenu.add(saveConfigurationPresetsMenuItem); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; final JMenuItem optionsMenuItem = new JMenuItem(); optionsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); getContentPane().add(binningLabel); springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 64, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1, SpringLayout.WEST, getContentPane()); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(labelImageDimensions_); springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, -5, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -25, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, getContentPane()); comboBinning_ = new JComboBox(); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeBinning(); } }); getContentPane().add(comboBinning_); springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 66, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 43, SpringLayout.NORTH, getContentPane()); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); getContentPane().add(cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, getContentPane()); configPad_ = new ConfigGroupPad(); configPad_.setFont(new Font("", Font.PLAIN, 10)); getContentPane().add(configPad_); springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 156, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, getContentPane()); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(this); getContentPane().add(configPadButtonPanel_); springLayout_.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, 158, SpringLayout.NORTH, getContentPane()); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration settings"); getContentPane().add(stateDeviceLabel); springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0, SpringLayout.SOUTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0, SpringLayout.NORTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150, SpringLayout.WEST, configPad_); springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0, SpringLayout.WEST, configPad_); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open Acquistion dialog"); buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Multi-D Acq."); getContentPane().add(buttonAcqSetup); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, getContentPane()); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.setAutoShutter(autoShutterCheckBox_.isSelected()); if (shutterLabel_.length() > 0) { try { setShutterButton(core_.getShutterOpen()); } catch (Exception e1) { ReportingUtils.showError(e1); } } if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); getContentPane().add(autoShutterCheckBox_); springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118 - 22, SpringLayout.NORTH, getContentPane()); final JButton burstButton = new JButton(); burstButton.setMargin(new Insets(2, 2, 2, 2)); burstButton.setIconTextGap(1); burstButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/film_go.png")); burstButton.setFont(new Font("Arial", Font.PLAIN, 10)); burstButton.setToolTipText("Open Burst dialog for fast sequence acquisition"); burstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); burstButton.setText("Burst"); getContentPane().add(burstButton); springLayout_.putConstraint(SpringLayout.SOUTH, burstButton, 113, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, burstButton, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, burstButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, burstButton, 7, SpringLayout.WEST, getContentPane()); final JButton refreshButton = new JButton(); refreshButton.setMargin(new Insets(2, 2, 2, 2)); refreshButton.setIconTextGap(1); refreshButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 135, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 114, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, getContentPane()); // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { running_ = false; closeSequence(); } @Override public void windowOpened(WindowEvent e) { // ------------------- // initialize hardware // ------------------- core_ = new CMMCore(); ReportingUtils.setCore(core_); core_.enableDebugLog(options_.debugLogEnabled); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version")); cameraLabel_ = new String(""); shutterLabel_ = new String(""); zStageLabel_ = new String(""); xyStageLabel_ = new String(""); engine_ = new AcquisitionWrapperEngine(); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); if (!options_.doNotAskForConfigFile) { MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); afMgr_ = new AutofocusManager(core_); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); loadPlugins(); toFront(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls initializeGUI(); initializePluginMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } // switch error reporting back on ReportingUtils.showErrorOn(true); } }); final JButton setRoiButton = new JButton(); setRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setROI(); } }); getContentPane().add(setRoiButton); springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 37, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JButton clearRoiButton = new JButton(); clearRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearROI(); } }); getContentPane().add(clearRoiButton); springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 70, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 40, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); getContentPane().add(regionOfInterestLabel); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, getContentPane()); contrastPanel_ = new ContrastPanel(); contrastPanel_.setFont(new Font("", Font.PLAIN, 10)); contrastPanel_.setContrastStretch(stretch); contrastPanel_.setBorder(new LineBorder(Color.black, 1, false)); getContentPane().add(contrastPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7, SpringLayout.WEST, getContentPane()); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); getContentPane().add(regionOfInterestLabel_1); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 139, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 81, SpringLayout.WEST, getContentPane()); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setToolTipText("Zoom in"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomInButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 110, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 80, SpringLayout.WEST, getContentPane()); final JButton zoomOutButton = new JButton(); zoomOutButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Zoom out"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomOutButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 143, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 113, SpringLayout.WEST, getContentPane()); // Profile // ------- final JLabel profileLabel_ = new JLabel(); profileLabel_.setFont(new Font("Arial", Font.BOLD, 11)); profileLabel_.setText("Profile"); getContentPane().add(profileLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, profileLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, profileLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, profileLabel_, 217, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, profileLabel_, 154, SpringLayout.WEST, getContentPane()); final JButton buttonProf = new JButton(); buttonProf.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); buttonProf.setFont(new Font("Arial", Font.PLAIN, 10)); buttonProf.setToolTipText("Open line profile window (requires line selection)"); buttonProf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); // buttonProf.setText("Profile"); getContentPane().add(buttonProf); springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 183, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 153, SpringLayout.WEST, getContentPane()); // Autofocus // ------- final JLabel autofocusLabel_ = new JLabel(); autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11)); autofocusLabel_.setText("Autofocus"); getContentPane().add(autofocusLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, autofocusLabel_, 274, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autofocusLabel_, 194, SpringLayout.WEST, getContentPane()); buttonAutofocus_ = new JButton(); buttonAutofocus_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/find.png")); buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocus_.setToolTipText("Autofocus now"); buttonAutofocus_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (afMgr_.getDevice() != null) { try { afMgr_.getDevice().fullFocus(); // or any other method from Autofocus.java API } catch (MMException mE) { ReportingUtils.showError(mE); } } } }); getContentPane().add(buttonAutofocus_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193, SpringLayout.WEST, getContentPane()); buttonAutofocusTools_ = new JButton(); buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/wrench_orange.png")); buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocusTools_.setToolTipText("Set autofocus options"); buttonAutofocusTools_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAutofocusDialog(); } }); getContentPane().add(buttonAutofocusTools_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226, SpringLayout.WEST, getContentPane()); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); getContentPane().add(saveConfigButton_); springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, -80, SpringLayout.EAST, getContentPane()); }
public MMStudioMainFrame(boolean pluginStatus) { super(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { ReportingUtils.showError(e, "An uncaught exception was thrown in thread " + t.getName() + "."); } }); options_ = new MMOptions(); options_.loadSettings(); guiColors_ = new GUIColors(); plugins_ = new ArrayList<PluginItem>(); gui_ = this; runsAsPlugin_ = pluginStatus; setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class, "icons/microscope.gif")); running_ = true; // !!! contrastSettings8_ = new ContrastSettings(); // contrastSettings16_ = new ContrastSettings(); acqMgr_ = new AcquisitionManager(); sysConfigFile_ = new String(System.getProperty("user.dir") + "/" + DEFAULT_CONFIG_FILE_NAME); if (options_.startupScript.length() > 0) { startupScriptFile_ = new String(System.getProperty("user.dir") + "/" + options_.startupScript); } else { startupScriptFile_ = ""; } ReportingUtils.SetContainingFrame(gui_); // set the location for app preferences mainPrefs_ = Preferences.userNodeForPackage(this.getClass()); systemPrefs_ = mainPrefs_; // check system preferences try { Preferences p = Preferences.systemNodeForPackage(this.getClass()); if (null != p) { // if we can not write to the systemPrefs, use AppPrefs instead if (JavaUtils.backingStoreAvailable(p)) { systemPrefs_ = p; } } } catch (Exception e) { ReportingUtils.logError(e); } // show registration dialog if not already registered // first check user preferences (for legacy compatibility reasons) boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!userReg) { boolean systemReg = systemPrefs_.getBoolean( RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false); if (!systemReg) { // prompt for registration info RegistrationDlg dlg = new RegistrationDlg(systemPrefs_); dlg.setVisible(true); } } // initialize timer ActionListener liveModeTimerHandler = new ActionListener() { public void actionPerformed(ActionEvent evt) { Thread.currentThread().setPriority(3); if (!isImageWindowOpen()) { // stop live acquisition if user closed the window enableLiveMode(false); return; } if (!isNewImageAvailable()) { return; } try { Object img; if (!liveModeFullyStarted_) { if (core_.getRemainingImageCount() > 0) { liveModeFullyStarted_ = true; } } if (liveModeFullyStarted_) { img = core_.getLastImage(); if (img != img_) { img_ = img; displayImage(img_); } } } catch (Exception e) { ReportingUtils.showError(e); return; } } }; liveModeTimer_ = new Timer((int) liveModeInterval_, liveModeTimerHandler); liveModeTimer_.stop(); // load application preferences // NOTE: only window size and position preferences are loaded, // not the settings for the camera and live imaging - // attempting to set those automatically on startup may cause problems // with the hardware int x = mainPrefs_.getInt(MAIN_FRAME_X, 100); int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100); int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 580); int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 451); boolean stretch = mainPrefs_.getBoolean(MAIN_STRETCH_CONTRAST, true); openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, ""); setBounds(x, y, width, height); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); springLayout_ = new SpringLayout(); getContentPane().setLayout(springLayout_); setTitle(MICRO_MANAGER_TITLE); setBackground(guiColors_.background.get((options_.displayBackground))); // Snap button // ----------- buttonSnap_ = new JButton(); buttonSnap_.setIconTextGap(6); buttonSnap_.setText("Snap"); buttonSnap_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera.png")); buttonSnap_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonSnap_.setToolTipText("Snap single image"); buttonSnap_.setMaximumSize(new Dimension(0, 0)); buttonSnap_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSnap(); } }); getContentPane().add(buttonSnap_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonSnap_, 25, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonSnap_, 4, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonSnap_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonSnap_, 7, SpringLayout.WEST, getContentPane()); // Initialize // ---------- // Exposure field // --------------- final JLabel label_1 = new JLabel(); label_1.setFont(new Font("Arial", Font.PLAIN, 10)); label_1.setText("Exposure [ms]"); getContentPane().add(label_1); springLayout_.putConstraint(SpringLayout.EAST, label_1, 198, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, label_1, 111, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, label_1, 39, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, label_1, 23, SpringLayout.NORTH, getContentPane()); textFieldExp_ = new JTextField(); textFieldExp_.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent fe) { setExposure(); } }); textFieldExp_.setFont(new Font("Arial", Font.PLAIN, 10)); textFieldExp_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setExposure(); } }); getContentPane().add(textFieldExp_); springLayout_.putConstraint(SpringLayout.SOUTH, textFieldExp_, 40, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, textFieldExp_, 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, textFieldExp_, 276, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, textFieldExp_, 203, SpringLayout.WEST, getContentPane()); // Live button // ----------- toggleButtonLive_ = new JToggleButton(); toggleButtonLive_.setMargin(new Insets(2, 2, 2, 2)); toggleButtonLive_.setIconTextGap(1); toggleButtonLive_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/camera_go.png")); toggleButtonLive_.setIconTextGap(6); toggleButtonLive_.setToolTipText("Continuous live view"); toggleButtonLive_.setFont(new Font("Arial", Font.PLAIN, 10)); toggleButtonLive_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!IsLiveModeOn()) { // Display interval for Live Mode changes as well setLiveModeInterval(); } enableLiveMode(!IsLiveModeOn()); } }); toggleButtonLive_.setText("Live"); getContentPane().add(toggleButtonLive_); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonLive_, 47, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonLive_, 26, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonLive_, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonLive_, 7, SpringLayout.WEST, getContentPane()); // Acquire button // ----------- JButton acquireButton = new JButton(); acquireButton.setMargin(new Insets(2, 2, 2, 2)); acquireButton.setIconTextGap(1); acquireButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/snapAppend.png")); acquireButton.setIconTextGap(6); acquireButton.setToolTipText("Acquire single frame"); acquireButton.setFont(new Font("Arial", Font.PLAIN, 10)); acquireButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { snapAndAddToImage5D(null); } }); acquireButton.setText("Acquire"); getContentPane().add(acquireButton); springLayout_.putConstraint(SpringLayout.SOUTH, acquireButton, 69, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, acquireButton, 48, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, acquireButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, acquireButton, 7, SpringLayout.WEST, getContentPane()); // Shutter button // -------------- toggleButtonShutter_ = new JToggleButton(); toggleButtonShutter_.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { try { if (toggleButtonShutter_.isSelected()) { setShutterButton(true); core_.setShutterOpen(true); } else { core_.setShutterOpen(false); setShutterButton(false); } } catch (Exception e1) { ReportingUtils.showError(e1); } } }); toggleButtonShutter_.setToolTipText("Open/close the shutter"); toggleButtonShutter_.setIconTextGap(6); toggleButtonShutter_.setFont(new Font("Arial", Font.BOLD, 10)); toggleButtonShutter_.setText("Open"); getContentPane().add(toggleButtonShutter_); springLayout_.putConstraint(SpringLayout.EAST, toggleButtonShutter_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, toggleButtonShutter_, 203, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, toggleButtonShutter_, 138 - 21, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, toggleButtonShutter_, 117 - 21, SpringLayout.NORTH, getContentPane()); // Active shutter label final JLabel activeShutterLabel = new JLabel(); activeShutterLabel.setFont(new Font("Arial", Font.PLAIN, 10)); activeShutterLabel.setText("Shutter"); getContentPane().add(activeShutterLabel); springLayout_.putConstraint(SpringLayout.SOUTH, activeShutterLabel, 108 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, activeShutterLabel, 95 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, activeShutterLabel, 160 - 2, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, activeShutterLabel, 113 - 2, SpringLayout.WEST, getContentPane()); // Active shutter Combo Box shutterComboBox_ = new JComboBox(); shutterComboBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (shutterComboBox_.getSelectedItem() != null) { core_.setShutterDevice((String) shutterComboBox_.getSelectedItem()); } } catch (Exception e) { ReportingUtils.showError(e); } return; } }); getContentPane().add(shutterComboBox_); springLayout_.putConstraint(SpringLayout.SOUTH, shutterComboBox_, 114 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, shutterComboBox_, 92 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, shutterComboBox_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, shutterComboBox_, 170, SpringLayout.WEST, getContentPane()); menuBar_ = new JMenuBar(); setJMenuBar(menuBar_); final JMenu fileMenu = new JMenu(); fileMenu.setText("File"); menuBar_.add(fileMenu); final JMenuItem openMenuItem = new JMenuItem(); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { new Thread() { @Override public void run() { openAcquisitionData(); } }.start(); } }); openMenuItem.setText("Open Acquisition Data..."); fileMenu.add(openMenuItem); fileMenu.addSeparator(); final JMenuItem loadState = new JMenuItem(); loadState.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadSystemState(); } }); loadState.setText("Load System State..."); fileMenu.add(loadState); final JMenuItem saveStateAs = new JMenuItem(); fileMenu.add(saveStateAs); saveStateAs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { saveSystemState(); } }); saveStateAs.setText("Save System State As..."); fileMenu.addSeparator(); final JMenuItem exitMenuItem = new JMenuItem(); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeSequence(); } }); fileMenu.add(exitMenuItem); exitMenuItem.setText("Exit"); final JMenu image5dMenu = new JMenu(); image5dMenu.setText("Image5D"); menuBar_.add(image5dMenu); final JMenuItem closeAllMenuItem = new JMenuItem(); closeAllMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { WindowManager.closeAllWindows(); } }); closeAllMenuItem.setText("Close All"); image5dMenu.add(closeAllMenuItem); final JMenuItem duplicateMenuItem = new JMenuItem(); duplicateMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Duplicate_Image5D duplicate = new Duplicate_Image5D(); duplicate.run(""); } }); duplicateMenuItem.setText("Duplicate"); image5dMenu.add(duplicateMenuItem); final JMenuItem cropMenuItem = new JMenuItem(); cropMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Crop_Image5D crop = new Crop_Image5D(); crop.run(""); } }); cropMenuItem.setText("Crop"); image5dMenu.add(cropMenuItem); final JMenuItem makeMontageMenuItem = new JMenuItem(); makeMontageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Make_Montage makeMontage = new Make_Montage(); makeMontage.run(""); } }); makeMontageMenuItem.setText("Make Montage"); image5dMenu.add(makeMontageMenuItem); final JMenuItem zProjectMenuItem = new JMenuItem(); zProjectMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Z_Project projection = new Z_Project(); projection.run(""); } }); zProjectMenuItem.setText("Z Project"); image5dMenu.add(zProjectMenuItem); final JMenuItem convertToRgbMenuItem = new JMenuItem(); convertToRgbMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB stackToRGB = new Image5D_Stack_to_RGB(); stackToRGB.run(""); } }); convertToRgbMenuItem.setText("Copy to RGB Stack(z)"); image5dMenu.add(convertToRgbMenuItem); final JMenuItem convertToRgbtMenuItem = new JMenuItem(); convertToRgbtMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Stack_to_RGB_t stackToRGB_t = new Image5D_Stack_to_RGB_t(); stackToRGB_t.run(""); } }); convertToRgbtMenuItem.setText("Copy to RGB Stack(t)"); image5dMenu.add(convertToRgbtMenuItem); final JMenuItem convertToStackMenuItem = new JMenuItem(); convertToStackMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_Stack image5DToStack = new Image5D_to_Stack(); image5DToStack.run(""); } }); convertToStackMenuItem.setText("Copy to Stack"); image5dMenu.add(convertToStackMenuItem); final JMenuItem convertToStacksMenuItem = new JMenuItem(); convertToStacksMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_Channels_to_Stacks image5DToStacks = new Image5D_Channels_to_Stacks(); image5DToStacks.run(""); } }); convertToStacksMenuItem.setText("Copy to Stacks (channels)"); image5dMenu.add(convertToStacksMenuItem); final JMenuItem volumeViewerMenuItem = new JMenuItem(); volumeViewerMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Image5D_to_VolumeViewer volumeViewer = new Image5D_to_VolumeViewer(); volumeViewer.run(""); } }); volumeViewerMenuItem.setText("VolumeViewer"); image5dMenu.add(volumeViewerMenuItem); final JMenuItem splitImageMenuItem = new JMenuItem(); splitImageMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { Split_Image5D splitImage = new Split_Image5D(); splitImage.run(""); } }); splitImageMenuItem.setText("SplitView"); image5dMenu.add(splitImageMenuItem); final JMenu toolsMenu = new JMenu(); toolsMenu.setText("Tools"); menuBar_.add(toolsMenu); final JMenuItem refreshMenuItem = new JMenuItem(); refreshMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/arrow_refresh.png")); refreshMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshMenuItem.setText("Refresh GUI"); toolsMenu.add(refreshMenuItem); final JMenuItem rebuildGuiMenuItem = new JMenuItem(); rebuildGuiMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { initializeGUI(); } }); rebuildGuiMenuItem.setText("Rebuild GUI"); toolsMenu.add(rebuildGuiMenuItem); toolsMenu.addSeparator(); final JMenuItem scriptPanelMenuItem = new JMenuItem(); toolsMenu.add(scriptPanelMenuItem); scriptPanelMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createScriptPanel(); } }); scriptPanelMenuItem.setText("Script Panel..."); final JMenuItem propertyEditorMenuItem = new JMenuItem(); toolsMenu.add(propertyEditorMenuItem); propertyEditorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createPropertyEditor(); } }); propertyEditorMenuItem.setText("Device/Property Browser..."); toolsMenu.addSeparator(); final JMenuItem xyListMenuItem = new JMenuItem(); xyListMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showXYPositionList(); } }); xyListMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/application_view_list.png")); xyListMenuItem.setText("XY List..."); toolsMenu.add(xyListMenuItem); final JMenuItem acquisitionMenuItem = new JMenuItem(); acquisitionMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); acquisitionMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film.png")); acquisitionMenuItem.setText("Multi-Dimensional Acquisition..."); toolsMenu.add(acquisitionMenuItem); final JMenuItem sequenceMenuItem = new JMenuItem(); sequenceMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); sequenceMenuItem.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "icons/film_go.png")); sequenceMenuItem.setText("Burst Acquisition..."); toolsMenu.add(sequenceMenuItem); final JMenuItem splitViewMenuItem = new JMenuItem(); splitViewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { splitViewDialog(); } }); splitViewMenuItem.setText("Split View..."); toolsMenu.add(splitViewMenuItem); centerAndDragMenuItem_ = new JCheckBoxMenuItem(); centerAndDragMenuItem_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (centerAndDragListener_ == null) { centerAndDragListener_ = new CenterAndDragListener(core_, gui_); } if (!centerAndDragListener_.isRunning()) { centerAndDragListener_.start(); centerAndDragMenuItem_.setSelected(true); } else { centerAndDragListener_.stop(); centerAndDragMenuItem_.setSelected(false); } mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected()); } }); centerAndDragMenuItem_.setText("Mouse Moves Stage"); centerAndDragMenuItem_.setSelected(mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false)); toolsMenu.add(centerAndDragMenuItem_); final JMenuItem calibrationMenuItem = new JMenuItem(); toolsMenu.add(calibrationMenuItem); calibrationMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createCalibrationListDlg(); } }); calibrationMenuItem.setText("Pixel Size Calibration..."); toolsMenu.add(calibrationMenuItem); toolsMenu.addSeparator(); final JMenuItem configuratorMenuItem = new JMenuItem(); configuratorMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if (configChanged_) { Object[] options = {"Yes", "No"}; int n = JOptionPane.showOptionDialog(null, "Save Changed Configuration?", "Micro-Manager", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == JOptionPane.YES_OPTION) { saveConfigPresets(); } configChanged_ = false; } // unload all devices before starting configurator core_.reset(); GUIUtils.preventDisplayAdapterChangeExceptions(); // run Configurator ConfiguratorDlg configurator = new ConfiguratorDlg(core_, sysConfigFile_); configurator.setVisible(true); GUIUtils.preventDisplayAdapterChangeExceptions(); // re-initialize the system with the new configuration file sysConfigFile_ = configurator.getFileName(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); loadSystemConfiguration(); GUIUtils.preventDisplayAdapterChangeExceptions(); } catch (Exception e) { ReportingUtils.showError(e); return; } } }); configuratorMenuItem.setText("Hardware Configuration Wizard..."); toolsMenu.add(configuratorMenuItem); final JMenuItem loadSystemConfigMenuItem = new JMenuItem(); toolsMenu.add(loadSystemConfigMenuItem); loadSystemConfigMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { loadConfiguration(); initializeGUI(); } }); loadSystemConfigMenuItem.setText("Load Hardware Configuration..."); switchConfigurationMenu_ = new JMenu(); for (int i=0; i<5; i++) { JMenuItem configItem = new JMenuItem(); configItem.setText(Integer.toString(i)); switchConfigurationMenu_.add(configItem); } switchConfigurationMenu_.setText("Switch Hardware Configuration"); toolsMenu.add(switchConfigurationMenu_); final JMenuItem saveConfigurationPresetsMenuItem = new JMenuItem(); saveConfigurationPresetsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); updateChannelCombos(); } }); saveConfigurationPresetsMenuItem.setText("Save Configuration Settings..."); toolsMenu.add(saveConfigurationPresetsMenuItem); toolsMenu.addSeparator(); final MMStudioMainFrame thisInstance = this; final JMenuItem optionsMenuItem = new JMenuItem(); optionsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { int oldBufsize = options_.circularBufferSizeMB; OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_, thisInstance); dlg.setVisible(true); // adjust memory footprint if necessary if (oldBufsize != options_.circularBufferSizeMB) { try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception exc) { ReportingUtils.showError(exc); } } } }); optionsMenuItem.setText("Options..."); toolsMenu.add(optionsMenuItem); final JLabel binningLabel = new JLabel(); binningLabel.setFont(new Font("Arial", Font.PLAIN, 10)); binningLabel.setText("Binning"); getContentPane().add(binningLabel); springLayout_.putConstraint(SpringLayout.SOUTH, binningLabel, 64, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, binningLabel, 43, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, binningLabel, 200 - 1, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, binningLabel, 112 - 1, SpringLayout.WEST, getContentPane()); labelImageDimensions_ = new JLabel(); labelImageDimensions_.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(labelImageDimensions_); springLayout_.putConstraint(SpringLayout.SOUTH, labelImageDimensions_, -5, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, labelImageDimensions_, -25, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, labelImageDimensions_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, labelImageDimensions_, 5, SpringLayout.WEST, getContentPane()); comboBinning_ = new JComboBox(); comboBinning_.setFont(new Font("Arial", Font.PLAIN, 10)); comboBinning_.setMaximumRowCount(4); comboBinning_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeBinning(); } }); getContentPane().add(comboBinning_); springLayout_.putConstraint(SpringLayout.EAST, comboBinning_, 275, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, comboBinning_, 200, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, comboBinning_, 66, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, comboBinning_, 43, SpringLayout.NORTH, getContentPane()); final JLabel cameraSettingsLabel = new JLabel(); cameraSettingsLabel.setFont(new Font("Arial", Font.BOLD, 11)); cameraSettingsLabel.setText("Camera settings"); getContentPane().add(cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, cameraSettingsLabel, 211, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, cameraSettingsLabel, 6, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, cameraSettingsLabel, 109, SpringLayout.WEST, getContentPane()); configPad_ = new ConfigGroupPad(); configPad_.setFont(new Font("", Font.PLAIN, 10)); getContentPane().add(configPad_); springLayout_.putConstraint(SpringLayout.EAST, configPad_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPad_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPad_, 156, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPad_, 21, SpringLayout.NORTH, getContentPane()); configPadButtonPanel_ = new ConfigPadButtonPanel(); configPadButtonPanel_.setConfigPad(configPad_); configPadButtonPanel_.setGUI(this); getContentPane().add(configPadButtonPanel_); springLayout_.putConstraint(SpringLayout.EAST, configPadButtonPanel_, -4, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, configPadButtonPanel_, 5, SpringLayout.EAST, comboBinning_); springLayout_.putConstraint(SpringLayout.SOUTH, configPadButtonPanel_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, configPadButtonPanel_, 158, SpringLayout.NORTH, getContentPane()); final JLabel stateDeviceLabel = new JLabel(); stateDeviceLabel.setFont(new Font("Arial", Font.BOLD, 11)); stateDeviceLabel.setText("Configuration settings"); getContentPane().add(stateDeviceLabel); springLayout_.putConstraint(SpringLayout.SOUTH, stateDeviceLabel, 0, SpringLayout.SOUTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.NORTH, stateDeviceLabel, 0, SpringLayout.NORTH, cameraSettingsLabel); springLayout_.putConstraint(SpringLayout.EAST, stateDeviceLabel, 150, SpringLayout.WEST, configPad_); springLayout_.putConstraint(SpringLayout.WEST, stateDeviceLabel, 0, SpringLayout.WEST, configPad_); final JButton buttonAcqSetup = new JButton(); buttonAcqSetup.setMargin(new Insets(2, 2, 2, 2)); buttonAcqSetup.setIconTextGap(1); buttonAcqSetup.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/film.png")); buttonAcqSetup.setToolTipText("Open Acquistion dialog"); buttonAcqSetup.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAcqSetup.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openAcqControlDialog(); } }); buttonAcqSetup.setText("Multi-D Acq."); getContentPane().add(buttonAcqSetup); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAcqSetup, 91, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAcqSetup, 70, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAcqSetup, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAcqSetup, 7, SpringLayout.WEST, getContentPane()); autoShutterCheckBox_ = new JCheckBox(); autoShutterCheckBox_.setFont(new Font("Arial", Font.PLAIN, 10)); autoShutterCheckBox_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { core_.setAutoShutter(autoShutterCheckBox_.isSelected()); if (shutterLabel_.length() > 0) { try { setShutterButton(core_.getShutterOpen()); } catch (Exception e1) { ReportingUtils.showError(e1); } } if (autoShutterCheckBox_.isSelected()) { toggleButtonShutter_.setEnabled(false); } else { toggleButtonShutter_.setEnabled(true); } } }); autoShutterCheckBox_.setIconTextGap(6); autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING); autoShutterCheckBox_.setText("Auto shutter"); getContentPane().add(autoShutterCheckBox_); springLayout_.putConstraint(SpringLayout.EAST, autoShutterCheckBox_, 202 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autoShutterCheckBox_, 110 - 3, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, autoShutterCheckBox_, 141 - 22, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autoShutterCheckBox_, 118 - 22, SpringLayout.NORTH, getContentPane()); final JButton burstButton = new JButton(); burstButton.setMargin(new Insets(2, 2, 2, 2)); burstButton.setIconTextGap(1); burstButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/film_go.png")); burstButton.setFont(new Font("Arial", Font.PLAIN, 10)); burstButton.setToolTipText("Open Burst dialog for fast sequence acquisition"); burstButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openSequenceDialog(); } }); burstButton.setText("Burst"); getContentPane().add(burstButton); springLayout_.putConstraint(SpringLayout.SOUTH, burstButton, 113, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, burstButton, 92, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, burstButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, burstButton, 7, SpringLayout.WEST, getContentPane()); final JButton refreshButton = new JButton(); refreshButton.setMargin(new Insets(2, 2, 2, 2)); refreshButton.setIconTextGap(1); refreshButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_refresh.png")); refreshButton.setFont(new Font("Arial", Font.PLAIN, 10)); refreshButton.setToolTipText("Refresh all GUI controls directly from the hardware"); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateGUI(true); } }); refreshButton.setText("Refresh"); getContentPane().add(refreshButton); springLayout_.putConstraint(SpringLayout.SOUTH, refreshButton, 135, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, refreshButton, 114, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, refreshButton, 95, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, refreshButton, 7, SpringLayout.WEST, getContentPane()); // add window listeners addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { running_ = false; closeSequence(); } @Override public void windowOpened(WindowEvent e) { // ------------------- // initialize hardware // ------------------- core_ = new CMMCore(); ReportingUtils.setCore(core_); core_.enableDebugLog(options_.debugLogEnabled); core_.logMessage("MM Studio version: " + getVersion()); core_.logMessage(core_.getVersionInfo()); core_.logMessage(core_.getAPIVersionInfo()); core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version")); cameraLabel_ = new String(""); shutterLabel_ = new String(""); zStageLabel_ = new String(""); xyStageLabel_ = new String(""); engine_ = new AcquisitionWrapperEngine(); // register callback for MMCore notifications, this is a global // to avoid garbage collection cb_ = new CoreEventCallback(); core_.registerCallback(cb_); try { core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB); } catch (Exception e2) { ReportingUtils.showError(e2); } MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow(); if (parent != null) { engine_.setParentGUI(parent); } loadMRUConfigFiles(); if (!options_.doNotAskForConfigFile) { MMIntroDlg introDlg = new MMIntroDlg(VERSION, MRUConfigFiles_); introDlg.setConfigFile(sysConfigFile_); introDlg.setVisible(true); sysConfigFile_ = introDlg.getConfigFile(); } saveMRUConfigFiles(); mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_); paint(MMStudioMainFrame.this.getGraphics()); afMgr_ = new AutofocusManager(core_); engine_.setCore(core_, afMgr_); posList_ = new PositionList(); engine_.setPositionList(posList_); // if an error occurred during config loading, // do not display more errors than needed if (!loadSystemConfiguration()) ReportingUtils.showErrorOn(false); executeStartupScript(); loadPlugins(); toFront(); // Create Multi-D window here but do not show it. // This window needs to be created in order to properly set the "ChannelGroup" // based on the Multi-D parameters acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this); addMMBackgroundListener(acqControlWin_); configPad_.setCore(core_); if (parent != null) { configPad_.setParentGUI(parent); } configPadButtonPanel_.setCore(core_); // initialize controls initializeGUI(); initializePluginMenu(); String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, ""); if (afMgr_.hasDevice(afDevice)) { try { afMgr_.selectDevice(afDevice); } catch (MMException e1) { // this error should never happen ReportingUtils.showError(e1); } } // switch error reporting back on ReportingUtils.showErrorOn(true); } }); final JButton setRoiButton = new JButton(); setRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/shape_handles.png")); setRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); setRoiButton.setToolTipText("Set Region Of Interest to selected rectangle"); setRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setROI(); } }); getContentPane().add(setRoiButton); springLayout_.putConstraint(SpringLayout.EAST, setRoiButton, 37, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, setRoiButton, 7, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, setRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, setRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JButton clearRoiButton = new JButton(); clearRoiButton.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/arrow_out.png")); clearRoiButton.setFont(new Font("Arial", Font.PLAIN, 10)); clearRoiButton.setToolTipText("Reset Region of Interest to full frame"); clearRoiButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { clearROI(); } }); getContentPane().add(clearRoiButton); springLayout_.putConstraint(SpringLayout.EAST, clearRoiButton, 70, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, clearRoiButton, 40, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.SOUTH, clearRoiButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, clearRoiButton, 154, SpringLayout.NORTH, getContentPane()); final JLabel regionOfInterestLabel = new JLabel(); regionOfInterestLabel.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel.setText("ROI"); getContentPane().add(regionOfInterestLabel); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel, 71, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel, 8, SpringLayout.WEST, getContentPane()); contrastPanel_ = new ContrastPanel(); contrastPanel_.setFont(new Font("", Font.PLAIN, 10)); contrastPanel_.setContrastStretch(stretch); contrastPanel_.setBorder(new LineBorder(Color.black, 1, false)); getContentPane().add(contrastPanel_); springLayout_.putConstraint(SpringLayout.SOUTH, contrastPanel_, -26, SpringLayout.SOUTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, contrastPanel_, 176, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, contrastPanel_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, contrastPanel_, 7, SpringLayout.WEST, getContentPane()); final JLabel regionOfInterestLabel_1 = new JLabel(); regionOfInterestLabel_1.setFont(new Font("Arial", Font.BOLD, 11)); regionOfInterestLabel_1.setText("Zoom"); getContentPane().add(regionOfInterestLabel_1); springLayout_.putConstraint(SpringLayout.SOUTH, regionOfInterestLabel_1, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, regionOfInterestLabel_1, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, regionOfInterestLabel_1, 139, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, regionOfInterestLabel_1, 81, SpringLayout.WEST, getContentPane()); final JButton zoomInButton = new JButton(); zoomInButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomIn(); } }); zoomInButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_in.png")); zoomInButton.setToolTipText("Zoom in"); zoomInButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomInButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomInButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomInButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomInButton, 110, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomInButton, 80, SpringLayout.WEST, getContentPane()); final JButton zoomOutButton = new JButton(); zoomOutButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { zoomOut(); } }); zoomOutButton.setIcon(SwingResourceManager.getIcon(MMStudioMainFrame.class, "/org/micromanager/icons/zoom_out.png")); zoomOutButton.setToolTipText("Zoom out"); zoomOutButton.setFont(new Font("Arial", Font.PLAIN, 10)); getContentPane().add(zoomOutButton); springLayout_.putConstraint(SpringLayout.SOUTH, zoomOutButton, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, zoomOutButton, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, zoomOutButton, 143, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, zoomOutButton, 113, SpringLayout.WEST, getContentPane()); // Profile // ------- final JLabel profileLabel_ = new JLabel(); profileLabel_.setFont(new Font("Arial", Font.BOLD, 11)); profileLabel_.setText("Profile"); getContentPane().add(profileLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, profileLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, profileLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, profileLabel_, 217, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, profileLabel_, 154, SpringLayout.WEST, getContentPane()); final JButton buttonProf = new JButton(); buttonProf.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/chart_curve.png")); buttonProf.setFont(new Font("Arial", Font.PLAIN, 10)); buttonProf.setToolTipText("Open line profile window (requires line selection)"); buttonProf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { openLineProfileWindow(); } }); // buttonProf.setText("Profile"); getContentPane().add(buttonProf); springLayout_.putConstraint(SpringLayout.SOUTH, buttonProf, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonProf, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonProf, 183, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonProf, 153, SpringLayout.WEST, getContentPane()); // Autofocus // ------- final JLabel autofocusLabel_ = new JLabel(); autofocusLabel_.setFont(new Font("Arial", Font.BOLD, 11)); autofocusLabel_.setText("Autofocus"); getContentPane().add(autofocusLabel_); springLayout_.putConstraint(SpringLayout.SOUTH, autofocusLabel_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, autofocusLabel_, 140, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, autofocusLabel_, 274, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, autofocusLabel_, 194, SpringLayout.WEST, getContentPane()); buttonAutofocus_ = new JButton(); buttonAutofocus_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/find.png")); buttonAutofocus_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocus_.setToolTipText("Autofocus now"); buttonAutofocus_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (afMgr_.getDevice() != null) { try { afMgr_.getDevice().fullFocus(); // or any other method from Autofocus.java API } catch (MMException mE) { ReportingUtils.showError(mE); } } } }); getContentPane().add(buttonAutofocus_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocus_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocus_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocus_, 223, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocus_, 193, SpringLayout.WEST, getContentPane()); buttonAutofocusTools_ = new JButton(); buttonAutofocusTools_.setIcon(SwingResourceManager.getIcon( MMStudioMainFrame.class, "/org/micromanager/icons/wrench_orange.png")); buttonAutofocusTools_.setFont(new Font("Arial", Font.PLAIN, 10)); buttonAutofocusTools_.setToolTipText("Set autofocus options"); buttonAutofocusTools_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAutofocusDialog(); } }); getContentPane().add(buttonAutofocusTools_); springLayout_.putConstraint(SpringLayout.SOUTH, buttonAutofocusTools_, 174, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, buttonAutofocusTools_, 154, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, buttonAutofocusTools_, 256, SpringLayout.WEST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, buttonAutofocusTools_, 226, SpringLayout.WEST, getContentPane()); saveConfigButton_ = new JButton(); saveConfigButton_.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { saveConfigPresets(); } }); saveConfigButton_.setToolTipText("Save current presets to the configuration file"); saveConfigButton_.setText("Save"); saveConfigButton_.setEnabled(false); getContentPane().add(saveConfigButton_); springLayout_.putConstraint(SpringLayout.SOUTH, saveConfigButton_, 20, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.NORTH, saveConfigButton_, 2, SpringLayout.NORTH, getContentPane()); springLayout_.putConstraint(SpringLayout.EAST, saveConfigButton_, -5, SpringLayout.EAST, getContentPane()); springLayout_.putConstraint(SpringLayout.WEST, saveConfigButton_, -80, SpringLayout.EAST, getContentPane()); }
diff --git a/srcj/com/sun/electric/tool/generator/PadGenerator.java b/srcj/com/sun/electric/tool/generator/PadGenerator.java index 91d6318f4..e0c75d14f 100755 --- a/srcj/com/sun/electric/tool/generator/PadGenerator.java +++ b/srcj/com/sun/electric/tool/generator/PadGenerator.java @@ -1,1194 +1,1195 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: PadGenerator.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.generator; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.geometry.Dimension2D; import com.sun.electric.database.geometry.EGraphics; import com.sun.electric.database.geometry.EPoint; import com.sun.electric.database.geometry.Orientation; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.geometry.PolyBase; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.hierarchy.Export; import com.sun.electric.database.hierarchy.Library; import com.sun.electric.database.hierarchy.View; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.database.text.CellName; import com.sun.electric.database.text.Name; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.PortInst; import com.sun.electric.database.variable.TextDescriptor; import com.sun.electric.database.variable.UserInterface; import com.sun.electric.lib.LibFile; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.technologies.Artwork; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.technology.technologies.Schematics; import com.sun.electric.tool.Job; import com.sun.electric.tool.JobException; import com.sun.electric.tool.io.FileType; import com.sun.electric.tool.io.input.LibraryFiles; import com.sun.electric.tool.routing.AutoStitch; import com.sun.electric.tool.user.CellChangeJobs; import com.sun.electric.tool.user.User; import com.sun.electric.tool.user.ViewChanges; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Class to generate pad frames from a specification file. */ public class PadGenerator { /** * Method to generate a pad frame from an array file. * Schedules a change job to generate the pad frame. * @param destLib destination library. * @param fileName the array file name. */ public static void makePadFrame(Library destLib, String fileName) { if (fileName == null) return; new MakePadFrame(destLib, fileName, Job.getUserInterface().getGridAlignment()); } /** * Method to generate a pad frame from an array file. * Presumes that it is being run from inside a change job. * @param destLib destination library. * @param fileName the array file name. * @param job the Job running this task (null if none). */ public static Cell makePadFrameUseJob(Library destLib, String fileName, Dimension2D alignment, Job job) { PadGenerator pg = new PadGenerator(destLib, fileName, alignment); return pg.makePadFrame(job); } private static class MakePadFrame extends Job { private Library destLib; private String fileName; private Cell frameCell; private Dimension2D alignment; private MakePadFrame(Library destLib, String fileName, Dimension2D alignment) { super("Pad Frame Generator", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER); this.destLib = destLib; this.fileName = fileName; this.alignment = alignment; startJob(); } public boolean doIt() throws JobException { frameCell = makePadFrameUseJob(destLib, fileName, alignment, this); fieldVariableChanged("frameCell"); return true; } public void terminateOK() { UserInterface ui = Job.getUserInterface(); ui.displayCell(frameCell); } } private Library destLib; // destination library private String fileName; // name of file with pad array instructions private Dimension2D alignment; // alignment amount private String padframename; // name of pad frame cell private String corename; // core cell to stick in pad frame private int lineno; // line no of the pad array file we are processing private Library cellLib; // library containing pad cells private boolean copycells; // if we copy cells into the library with the pad ring private List<View> views; // list of strings defining views of pad frame to create. private int angle; // angle of placed instances private HashMap<String,ArrayAlign> alignments; // how to align adjacent instances private HashMap<String,PadExports> exports; // which ports to export private List<Object> orderedCommands; // list of orderedCommands to do private boolean coreAllOnOneSide = false; private static class ArrayAlign { int lineno; String cellname; String inport; String outport; } private static class PadExports { int lineno; String cellname; String padname; String corename; } private static class PlacePad { int lineno; String cellname; String exportsname; int gap; NodeInst ni; List<PortAssociate> associations; List<ExportAssociate> exportAssociations; Double locx; Double locy; } private static class Rotation { int angle; } private static class ReverseDirection { } private static class PortAssociate { boolean export; String portname; String assocname; } private static class ExportAssociate { String padportName; String exportName; } private PadGenerator(Library destLib, String fileName, Dimension2D alignment) { this.destLib = destLib; this.fileName = fileName; this.alignment = alignment; alignments = new HashMap<String,ArrayAlign>(); exports = new HashMap<String,PadExports>(); views = new ArrayList<View>(); angle = 0; lineno = 1; orderedCommands = new ArrayList<Object>(); } private Cell makePadFrame(Job job) { String lineRead; File inputFile = new File(fileName); if (inputFile == null || !inputFile.canRead()) { System.out.println("Error reading file "+fileName); return null; } try { FileReader readFile = new FileReader(inputFile); BufferedReader readLine = new BufferedReader(readFile); lineRead = readLine.readLine(); while (lineRead != null) { StringTokenizer str = new StringTokenizer(lineRead, " \t"); if (str.hasMoreTokens()) { String keyWord = str.nextToken(); if (keyWord.charAt(0) != ';') { do { if (keyWord.equals("celllibrary")) { if (!processCellLibrary(str)) return null; continue; } else if (keyWord.equals("views")) { if (!processViews(str)) return null; continue; } else if (keyWord.equals("cell")) { if (!processCell(str)) return null; continue; } else if (keyWord.equals("core")) { if (!processCore(str)) return null; continue; } else if (keyWord.equals("rotate")) { if (!processRotate(str)) return null; continue; } else if (keyWord.equals("reverse")) { if (!processReverse(str)) return null; continue; } else if (keyWord.equals("align")) { if (!processAlign(str)) return null; continue; } else if (keyWord.equals("export")) { if (!processExport(str)) return null; continue; } else if (keyWord.equals("place")) { if (!processPlace(str)) return null; continue; } else if (keyWord.equals("coreExportsAllOnOneSideOfIcon")) { coreAllOnOneSide = true; continue; } System.out.println("Line " + lineno + ": unknown keyword'" + keyWord + "'"); break; } while (str.hasMoreTokens()); } } lineRead = readLine.readLine(); lineno++; } } catch (IOException e1) {} Cell frameCell = createPadFrames(job); return frameCell; } /** * Process the celllibrary keyword * @return true on success, false on error. */ private boolean processCellLibrary(StringTokenizer str) { String keyWord; if (str.hasMoreTokens()) { keyWord = str.nextToken(); URL fileURL = TextUtils.makeURLToFile(keyWord); cellLib = Library.findLibrary(TextUtils.getFileNameWithoutExtension(fileURL)); if (cellLib == null) { // library does not exist: see if in same directory is pad frame file StringBuffer errmsg = new StringBuffer(); String fileDir = TextUtils.getFilePath(TextUtils.makeURLToFile(fileName)); fileURL = TextUtils.makeURLToFile(fileDir + keyWord); if (!TextUtils.URLExists(fileURL, errmsg)) { // library does not exist: see if file can be found locally if (!TextUtils.URLExists(fileURL, errmsg)) { // try the Electric library area fileURL = LibFile.getLibFile(keyWord); if (!TextUtils.URLExists(fileURL, errmsg)) { System.out.println(errmsg.toString()); return false; } } } FileType style = FileType.DEFAULTLIB; if (TextUtils.getExtension(fileURL).equals("txt")) style = FileType.READABLEDUMP; if (TextUtils.getExtension(fileURL).equals("elib")) style = FileType.ELIB; cellLib = LibraryFiles.readLibrary(fileURL, null, style, false); if (cellLib == null) { err("cannot read library " + keyWord); return false; } } } if (str.hasMoreTokens()) { keyWord = str.nextToken(); if (keyWord.equals("copy")) copycells = true; } return true; } /** * Process any Views. * @return true on success, false on error. */ private boolean processViews(StringTokenizer str) { String keyWord; while (str.hasMoreTokens()) { keyWord = str.nextToken(); View view = View.findView(keyWord); if (view != null) views.add(view); else err("Unknown view '" + keyWord + "', ignoring"); } return true; } /** * Process the cell keyword * @return true on success, false on error. */ private boolean processCell(StringTokenizer str) { if (str.hasMoreTokens()) { padframename = str.nextToken(); return true; } return false; } /** * Process the core keyword * @return true on success, false on error. */ private boolean processCore(StringTokenizer str) { if (str.hasMoreTokens()) { corename = str.nextToken(); return true; } return false; } /** * Process the rotate keyword * @return true on success, false on error. */ private boolean processRotate(StringTokenizer str) { String keyWord; int angle = 0; if (str.hasMoreTokens()) { keyWord = str.nextToken(); if (keyWord.equals("c")) { angle = 2700; } else if (keyWord.equals("cc")) { angle = 900; } else { System.out.println("Line " + lineno + ": incorrect rotation " + keyWord); return false; } Rotation rot = new Rotation(); rot.angle = angle; orderedCommands.add(rot); return true; } return false; } private boolean processReverse(StringTokenizer str) { orderedCommands.add(new ReverseDirection()); return true; } /** * Process the align keyword * @return true on success, false on error. */ private boolean processAlign(StringTokenizer str) { String keyWord; ArrayAlign aa = new ArrayAlign(); aa.lineno = lineno; keyWord = str.nextToken(); if (keyWord.equals("")) { System.out.println("Line " + lineno + ": missing 'cell' name"); return false; } aa.cellname = keyWord; keyWord = str.nextToken(); if (keyWord.equals("")) { System.out.println("Line " + lineno + ": missing 'in port' name"); return false; } aa.inport = keyWord; keyWord = str.nextToken(); if (keyWord.equals("")) { System.out.println("Line " + lineno + ": missing 'out port' name"); return false; } aa.outport = keyWord; alignments.put(aa.cellname, aa); return true; } /** * Process the export keyword * @return true on success, false on error. */ private boolean processExport(StringTokenizer str) { String keyWord; PadExports pe = new PadExports(); pe.lineno = lineno; pe.padname = null; pe.corename = null; keyWord = str.nextToken(); if (keyWord.equals("")) { System.out.println("Line " + lineno + ": missing 'cell' name"); return false; } pe.cellname = keyWord; if (str.hasMoreTokens()) { keyWord = str.nextToken(); pe.padname = keyWord; if (str.hasMoreTokens()) { keyWord = str.nextToken(); pe.corename = keyWord; } } exports.put(pe.cellname, pe); return true; } private boolean processPlace(StringTokenizer str) { PlacePad pad = new PlacePad(); pad.lineno = lineno; pad.exportsname = null; pad.gap = 0; pad.ni = null; pad.associations = new ArrayList<PortAssociate>(); pad.exportAssociations = new ArrayList<ExportAssociate>(); pad.locx = null; pad.locy = null; if (!str.hasMoreTokens()) { err("Cell name missing"); return false; } pad.cellname = str.nextToken(); while (str.hasMoreTokens()) { String keyWord = str.nextToken(); if (keyWord.equals("export")) { // export xxx=xxxx if (!str.hasMoreTokens()) { err("Missing export assignment after 'export' keyword"); return false; } keyWord = str.nextToken(); ExportAssociate ea = new ExportAssociate(); ea.padportName = getLHS(keyWord); if (ea.padportName == null) { err("Bad export assignment after 'export' keyword"); return false; } ea.exportName = getRHS(keyWord, str); if (ea.exportName == null) { err("Bad export assignment after 'export' keyword"); return false; } pad.exportAssociations.add(ea); } else { // name=xxxx or gap=xxxx String lhs = getLHS(keyWord); String rhs = getRHS(keyWord, str); if (lhs == null || rhs == null) { err("Parse error on assignment of " + keyWord); return false; } if (lhs.equals("gap")) { try { pad.gap = Integer.parseInt(rhs); } catch (java.lang.NumberFormatException e) { err("Error parsing integer for 'gap' = " + rhs); return false; } } else if (lhs.equals("name")) { pad.exportsname = rhs; } else if (lhs.equals("x")) { try { pad.locx = new Double(rhs); } catch (NumberFormatException e) { System.out.println(e.getMessage()); pad.locx = null; } } else if (lhs.equals("y")) { try { pad.locy = new Double(rhs); } catch (NumberFormatException e) { System.out.println(e.getMessage()); pad.locy = null; } } else { // port association PortAssociate pa = new PortAssociate(); pa.export = false; pa.portname = lhs; pa.assocname = rhs; pad.associations.add(pa); } } } orderedCommands.add(pad); return true; } private String getLHS(String keyword) { if (keyword.indexOf("=") != -1) { return keyword.substring(0, keyword.indexOf("=")); } return keyword; } private String getRHS(String keyword, StringTokenizer str) { if (keyword.indexOf("=") != -1) { if (keyword.substring(keyword.indexOf("=") + 1).equals("")) { // LHS= RHS if (!str.hasMoreTokens()) return null; return str.nextToken(); } // LHS=RHS return keyword.substring(keyword.indexOf("=") + 1); } if (!str.hasMoreTokens()) return null; keyword = str.nextToken(); if (keyword.equals("=")) { // LHS = RHS if (!str.hasMoreTokens()) return null; return str.nextToken(); } // LHS =RHS return keyword.substring(keyword.indexOf("=") + 1); } /** * Print the error message with the current line number. * @param msg */ private void err(String msg) { System.out.println("Line " + lineno + ": " + msg); } private Cell createPadFrames(Job job) { Cell frameCell = null; if (views.size() == 0) { frameCell = createPadFrame(padframename, View.LAYOUT, job); } else { for (View view : views) { if (view == View.SCHEMATIC) view = View.ICON; frameCell = createPadFrame(padframename, view, job); } } return frameCell; } private Cell createPadFrame(String name, View view, Job job) { angle = 0; // first, try to create cell CellName n = CellName.parseName(name); if (n != null && (n.getView() == null || n.getView() == View.UNKNOWN)) { // no view in cell name, append appropriately if (view == null) { name = name + "{lay}"; } else { if (view == View.ICON) { // create a schematic, place icons of pads in it name = name + "{sch}"; } else { name = name + "{" + view.getAbbreviation() + "}"; } } } Cell framecell = Cell.makeInstance(destLib, name); if (framecell == null) { System.out.println("Could not create pad frame Cell: " + name); return null; } List<Export> padPorts = new ArrayList<Export>(); List<Export> corePorts = new ArrayList<Export>(); NodeInst lastni = null; int lastRotate = 0; String lastpadname = null; boolean reversed = false; // cycle through all orderedCommands, doing them for (Object obj : orderedCommands) { // Rotation commands are ordered with respect to Place commands. if (obj instanceof Rotation) { angle = (angle + ((Rotation) obj).angle) % 3600; continue; } if (obj instanceof ReverseDirection) { reversed = !reversed; continue; } // otherwise this is a Place command PlacePad pad = (PlacePad) obj; lineno = pad.lineno; // get cell String cellname = pad.cellname; if (!cellname.endsWith("}")) { if (view != null) cellname = cellname + "{" + view.getAbbreviation() + "}"; } Cell cell = cellLib.findNodeProto(cellname); if (cell == null) { err("Could not create pad Cell: " + cellname); continue; } // if copying cell, copy it into current library if (copycells) { Cell existing = cell; cell = null; for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { List<Cell> fromCells = new ArrayList<Cell>(); fromCells.add(existing); CellChangeJobs.copyRecursively(fromCells, destLib, false, false, false, true, true); for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { err("Could not copy in pad Cell " + cellname); continue; } } } // get array alignment for this cell ArrayAlign aa = alignments.get(pad.cellname); if (aa == null) { err("No port alignment for cell " + pad.cellname); continue; } int gapx = 0, gapy = 0; double centerX = 0, centerY = 0; if (lastni != null) { // get info on last nodeinst created ArrayAlign lastaa = alignments.get(lastpadname); // get previous node's outport - use it to place this nodeinst PortProto pp = (lastni.getProto()).findPortProto(lastaa.outport); if (pp == null) { err("no port called '" + lastaa.outport + "' on " + lastni); continue; } Poly poly = (lastni.findPortInstFromProto(pp)).getPoly(); centerX = poly.getCenterX(); centerY = poly.getCenterY(); } Point2D pointCenter = new Point2D.Double(centerX, centerY); boolean flipLR = false; boolean flipUD = false; if (reversed) flipUD = true; Orientation orient = Orientation.fromJava(angle, flipLR, flipUD); NodeInst ni = NodeInst.makeInstance(cell, pointCenter, cell.getDefWidth(), cell.getDefHeight(), framecell, orient, null, 0); if (ni == null) { err("problem creating" + cell + " instance"); continue; } if (lastni != null) { int gap = pad.gap; if (reversed) gap = -gap; switch (lastRotate) { case 0: gapx = gap; gapy = 0; break; case 900: gapx = 0; gapy = gap; break; case 1800: gapx = -gap; gapy = 0; break; case 2700: gapx = 0; gapy = -gap; break; } PortProto inport = cell.findPortProto(aa.inport); if (inport == null) { err("No port called '" + aa.inport + "' on " + cell); continue; } Poly poly = ni.findPortInstFromProto(inport).getPoly(); double tempx = centerX - poly.getCenterX() + gapx; double tempy = centerY - poly.getCenterY() + gapy; ni.move(tempx, tempy); } double dx = 0, dy = 0; if (pad.locx != null) dx = pad.locx.doubleValue() - ni.getAnchorCenterX(); if (pad.locy != null) dy = pad.locy.doubleValue() - ni.getAnchorCenterY(); ni.move(dx, dy); // create exports // get export for this cell, if any if (pad.exportsname != null) { PadExports pe = exports.get(pad.cellname); if (pe != null) { // pad export Export pppad = cell.findExport(pe.padname); if (pppad == null) { err("no port called '" + pe.padname + "' on Cell " + cell.noLibDescribe()); } else { pppad = Export.newInstance(framecell, ni.findPortInstFromProto(pppad), pad.exportsname); if (pppad == null) err("Creating export " + pad.exportsname); else { TextDescriptor td = pppad.getTextDescriptor(Export.EXPORT_NAME); pppad.setTextDescriptor(Export.EXPORT_NAME, td.withAbsSize(14)); padPorts.add(pppad); } } // core export if (pe.corename != null) { Export ppcore = cell.findExport(pe.corename); if (ppcore == null) { err("no port called '" + pe.corename + "' on Cell " + cell.noLibDescribe()); } else { ppcore = Export.newInstance(framecell, ni.findPortInstFromProto(ppcore), "core_" + pad.exportsname); if (ppcore == null) err("Creating export core_" + pad.exportsname); else { TextDescriptor td = ppcore.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(ppcore); ppcore.setTextDescriptor(Export.EXPORT_NAME, td); } } } else { corePorts.add(null); } } } // create exports from export pad=name command for (ExportAssociate ea : pad.exportAssociations) { Export pp = cell.findExport(ea.padportName); if (pp == null) { err("no port called '" + ea.padportName + "' on Cell " + cell.noLibDescribe()); } else { pp = Export.newInstance(framecell, ni.findPortInstFromProto(pp), ea.exportName); if (pp == null) err("Creating export "+ea.exportName); else { TextDescriptor td = pp.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(pp); pp.setTextDescriptor(Export.EXPORT_NAME, td); } } } lastni = ni; lastRotate = angle; lastpadname = pad.cellname; pad.ni = ni; } // auto stitch everything AutoStitch.runAutoStitch(framecell, null, null, job, null, null, true, false, false); if (corename != null) { // first, try to create cell String corenameview = corename; - if (view != null) + CellName coreName = CellName.parseName(corename); + if (view != null && coreName.getView() == View.UNKNOWN) { corenameview = corename + "{" + view.getAbbreviation() + "}"; } Cell corenp = destLib.findNodeProto(corenameview); if (corenp == null) { System.out.println("Line " + lineno + ": cannot find core cell " + corenameview); } else { Rectangle2D bounds = framecell.getBounds(); Point2D center = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY()); DBMath.gridAlign(center, alignment); NodeInst ni = NodeInst.makeInstance(corenp, center, corenp.getDefWidth(), corenp.getDefHeight(), framecell); Map<Export,PortInst> trueBusEnd = new HashMap<Export,PortInst>(); for (Object obj : orderedCommands) { if (obj instanceof PlacePad) { PlacePad pad = (PlacePad) obj; for (PortAssociate pa : pad.associations) { if (pad.ni == null) continue; boolean nameArc = false; PortInst pi1 = null; PortProto corepp = corenp.findPortProto(pa.assocname); if (corepp != null) pi1 = ni.findPortInstFromProto(corepp); if (pi1 == null) { // see if there are bus ports on the core for(Iterator<PortProto> it = corenp.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); Name eName = e.getNameKey(); int wid = eName.busWidth(); if (wid <= 1) continue; for(int i=0; i<wid; i++) { if (eName.subname(i).toString().equals(pa.assocname)) { pi1 = trueBusEnd.get(e); if (pi1 == null) { // make a short bus arc from the port to a bus pin which gets used for connections PortInst pi = ni.findPortInstFromProto(e); PolyBase portPoly = pi.getPoly(); Rectangle2D portRect = portPoly.getBounds2D(); PrimitiveNode busPinProto = Schematics.tech().busPinNode; NodeInst busPin = NodeInst.makeInstance(busPinProto, new EPoint(portRect.getCenterX(), portRect.getCenterY()), busPinProto.getDefWidth(), busPinProto.getDefHeight(), framecell); pi1 = busPin.getOnlyPortInst(); ArcProto busArcProto = Schematics.tech().bus_arc; ArcInst.makeInstance(busArcProto, pi, pi1); trueBusEnd.put(e, pi1); } nameArc = true; break; } } if (pi1 != null) break; } } if (pi1 == null) { PortInst pi = pad.ni.findPortInst(pa.portname); Export.newInstance(pad.ni.getParent(), pi, pa.assocname); continue; } PortInst pi2 = pad.ni.findPortInst(pa.portname); ArcProto ap = Generic.tech().unrouted_arc; ArcInst ai = ArcInst.newInstanceBase(ap, ap.getDefaultLambdaBaseWidth(), pi1, pi2); if (nameArc) { ai.setName(pa.assocname); } else { // give generated name based on the connection String netName = "PADFRAME"; if (pad.exportAssociations != null && pad.exportAssociations.size() > 0) netName += "_" + pad.exportAssociations.get(0).exportName; netName += "_" + pa.assocname; ai.setName(netName); } } } } } } if (view == View.ICON) { // This is a crock until the functionality here can be folded // into CircuitChanges.makeIconViewCommand() // get icon style controls double leadLength = User.getIconGenLeadLength(); double leadSpacing = User.getIconGenLeadSpacing(); // create the new icon cell String iconCellName = framecell.getName() + "{ic}"; Cell iconCell = Cell.makeInstance(destLib, iconCellName); if (iconCell == null) { Job.getUserInterface().showErrorMessage("Cannot create Icon cell " + iconCellName, "Icon creation failed"); return framecell; } iconCell.setWantExpanded(); // determine the size of the "black box" core double ySize = Math.max(Math.max(padPorts.size(), corePorts.size()), 5) * leadSpacing; double xSize = 3 * leadSpacing; // create the "black box" NodeInst bbNi = null; if (User.isIconGenDrawBody()) { bbNi = NodeInst.newInstance(Artwork.tech().openedThickerPolygonNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); if (bbNi == null) return framecell; bbNi.newVar(Artwork.ART_COLOR, new Integer(EGraphics.RED)); EPoint[] points = new EPoint[5]; points[0] = new EPoint(-0.5 * xSize, -0.5 * ySize); points[1] = new EPoint(-0.5 * xSize, 0.5 * ySize); points[2] = new EPoint(0.5 * xSize, 0.5 * ySize); points[3] = new EPoint(0.5 * xSize, -0.5 * ySize); points[4] = new EPoint(-0.5 * xSize, -0.5 * ySize); bbNi.setTrace(points); // put the original cell name on it bbNi.newDisplayVar(Schematics.SCHEM_FUNCTION, framecell.getName()); } // get icon preferences int exportTech = User.getIconGenExportTech(); boolean drawLeads = User.isIconGenDrawLeads(); int exportStyle = User.getIconGenExportStyle(); int exportLocation = User.getIconGenExportLocation(); boolean ad = User.isIconsAlwaysDrawn(); if (coreAllOnOneSide) { List<Export> padTemp = new ArrayList<Export>(); List<Export> coreTemp = new ArrayList<Export>(); for (Export pp : padPorts) { if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } for (Export pp : corePorts) { if (pp == null) { coreTemp.add(pp); continue; } if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } padPorts = padTemp; corePorts = coreTemp; } // place pins around the Black Box int total = 0; int leftSide = padPorts.size(); int rightSide = corePorts.size(); for (Export pp : padPorts) { if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = -xSize / 2; xPos = xBBPos - leadLength; if (leftSide * 2 < rightSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (leftSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 0, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } total = 0; for (Export pp : corePorts) { if (pp == null) { total++; continue; } if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = xSize / 2; xPos = xBBPos + leadLength; if (rightSide * 2 < leftSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (rightSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 1, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } // if no body, leads, or cell center is drawn, and there is only 1 export, add more if (!User.isIconGenDrawBody() && !User.isIconGenDrawLeads() && User.isPlaceCellCenter() && total <= 1) { NodeInst.newInstance(Generic.tech().invisiblePinNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); } // place an icon in the schematic int exampleLocation = User.getIconGenInstanceLocation(); Point2D iconPos = new Point2D.Double(0, 0); Rectangle2D cellBounds = framecell.getBounds(); Rectangle2D iconBounds = iconCell.getBounds(); double halfWidth = iconBounds.getWidth() / 2; double halfHeight = iconBounds.getHeight() / 2; switch (exampleLocation) { case 0: // upper-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMaxY() + halfHeight); break; case 1: // upper-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMaxY() + halfHeight); break; case 2: // lower-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMinY() - halfHeight); break; case 3: // lower-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMinY() - halfHeight); break; } DBMath.gridAlign(iconPos, alignment); double px = iconCell.getBounds().getWidth(); double py = iconCell.getBounds().getHeight(); NodeInst.makeInstance(iconCell, iconPos, px, py, framecell); } return framecell; } }
true
true
private Cell createPadFrame(String name, View view, Job job) { angle = 0; // first, try to create cell CellName n = CellName.parseName(name); if (n != null && (n.getView() == null || n.getView() == View.UNKNOWN)) { // no view in cell name, append appropriately if (view == null) { name = name + "{lay}"; } else { if (view == View.ICON) { // create a schematic, place icons of pads in it name = name + "{sch}"; } else { name = name + "{" + view.getAbbreviation() + "}"; } } } Cell framecell = Cell.makeInstance(destLib, name); if (framecell == null) { System.out.println("Could not create pad frame Cell: " + name); return null; } List<Export> padPorts = new ArrayList<Export>(); List<Export> corePorts = new ArrayList<Export>(); NodeInst lastni = null; int lastRotate = 0; String lastpadname = null; boolean reversed = false; // cycle through all orderedCommands, doing them for (Object obj : orderedCommands) { // Rotation commands are ordered with respect to Place commands. if (obj instanceof Rotation) { angle = (angle + ((Rotation) obj).angle) % 3600; continue; } if (obj instanceof ReverseDirection) { reversed = !reversed; continue; } // otherwise this is a Place command PlacePad pad = (PlacePad) obj; lineno = pad.lineno; // get cell String cellname = pad.cellname; if (!cellname.endsWith("}")) { if (view != null) cellname = cellname + "{" + view.getAbbreviation() + "}"; } Cell cell = cellLib.findNodeProto(cellname); if (cell == null) { err("Could not create pad Cell: " + cellname); continue; } // if copying cell, copy it into current library if (copycells) { Cell existing = cell; cell = null; for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { List<Cell> fromCells = new ArrayList<Cell>(); fromCells.add(existing); CellChangeJobs.copyRecursively(fromCells, destLib, false, false, false, true, true); for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { err("Could not copy in pad Cell " + cellname); continue; } } } // get array alignment for this cell ArrayAlign aa = alignments.get(pad.cellname); if (aa == null) { err("No port alignment for cell " + pad.cellname); continue; } int gapx = 0, gapy = 0; double centerX = 0, centerY = 0; if (lastni != null) { // get info on last nodeinst created ArrayAlign lastaa = alignments.get(lastpadname); // get previous node's outport - use it to place this nodeinst PortProto pp = (lastni.getProto()).findPortProto(lastaa.outport); if (pp == null) { err("no port called '" + lastaa.outport + "' on " + lastni); continue; } Poly poly = (lastni.findPortInstFromProto(pp)).getPoly(); centerX = poly.getCenterX(); centerY = poly.getCenterY(); } Point2D pointCenter = new Point2D.Double(centerX, centerY); boolean flipLR = false; boolean flipUD = false; if (reversed) flipUD = true; Orientation orient = Orientation.fromJava(angle, flipLR, flipUD); NodeInst ni = NodeInst.makeInstance(cell, pointCenter, cell.getDefWidth(), cell.getDefHeight(), framecell, orient, null, 0); if (ni == null) { err("problem creating" + cell + " instance"); continue; } if (lastni != null) { int gap = pad.gap; if (reversed) gap = -gap; switch (lastRotate) { case 0: gapx = gap; gapy = 0; break; case 900: gapx = 0; gapy = gap; break; case 1800: gapx = -gap; gapy = 0; break; case 2700: gapx = 0; gapy = -gap; break; } PortProto inport = cell.findPortProto(aa.inport); if (inport == null) { err("No port called '" + aa.inport + "' on " + cell); continue; } Poly poly = ni.findPortInstFromProto(inport).getPoly(); double tempx = centerX - poly.getCenterX() + gapx; double tempy = centerY - poly.getCenterY() + gapy; ni.move(tempx, tempy); } double dx = 0, dy = 0; if (pad.locx != null) dx = pad.locx.doubleValue() - ni.getAnchorCenterX(); if (pad.locy != null) dy = pad.locy.doubleValue() - ni.getAnchorCenterY(); ni.move(dx, dy); // create exports // get export for this cell, if any if (pad.exportsname != null) { PadExports pe = exports.get(pad.cellname); if (pe != null) { // pad export Export pppad = cell.findExport(pe.padname); if (pppad == null) { err("no port called '" + pe.padname + "' on Cell " + cell.noLibDescribe()); } else { pppad = Export.newInstance(framecell, ni.findPortInstFromProto(pppad), pad.exportsname); if (pppad == null) err("Creating export " + pad.exportsname); else { TextDescriptor td = pppad.getTextDescriptor(Export.EXPORT_NAME); pppad.setTextDescriptor(Export.EXPORT_NAME, td.withAbsSize(14)); padPorts.add(pppad); } } // core export if (pe.corename != null) { Export ppcore = cell.findExport(pe.corename); if (ppcore == null) { err("no port called '" + pe.corename + "' on Cell " + cell.noLibDescribe()); } else { ppcore = Export.newInstance(framecell, ni.findPortInstFromProto(ppcore), "core_" + pad.exportsname); if (ppcore == null) err("Creating export core_" + pad.exportsname); else { TextDescriptor td = ppcore.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(ppcore); ppcore.setTextDescriptor(Export.EXPORT_NAME, td); } } } else { corePorts.add(null); } } } // create exports from export pad=name command for (ExportAssociate ea : pad.exportAssociations) { Export pp = cell.findExport(ea.padportName); if (pp == null) { err("no port called '" + ea.padportName + "' on Cell " + cell.noLibDescribe()); } else { pp = Export.newInstance(framecell, ni.findPortInstFromProto(pp), ea.exportName); if (pp == null) err("Creating export "+ea.exportName); else { TextDescriptor td = pp.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(pp); pp.setTextDescriptor(Export.EXPORT_NAME, td); } } } lastni = ni; lastRotate = angle; lastpadname = pad.cellname; pad.ni = ni; } // auto stitch everything AutoStitch.runAutoStitch(framecell, null, null, job, null, null, true, false, false); if (corename != null) { // first, try to create cell String corenameview = corename; if (view != null) { corenameview = corename + "{" + view.getAbbreviation() + "}"; } Cell corenp = destLib.findNodeProto(corenameview); if (corenp == null) { System.out.println("Line " + lineno + ": cannot find core cell " + corenameview); } else { Rectangle2D bounds = framecell.getBounds(); Point2D center = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY()); DBMath.gridAlign(center, alignment); NodeInst ni = NodeInst.makeInstance(corenp, center, corenp.getDefWidth(), corenp.getDefHeight(), framecell); Map<Export,PortInst> trueBusEnd = new HashMap<Export,PortInst>(); for (Object obj : orderedCommands) { if (obj instanceof PlacePad) { PlacePad pad = (PlacePad) obj; for (PortAssociate pa : pad.associations) { if (pad.ni == null) continue; boolean nameArc = false; PortInst pi1 = null; PortProto corepp = corenp.findPortProto(pa.assocname); if (corepp != null) pi1 = ni.findPortInstFromProto(corepp); if (pi1 == null) { // see if there are bus ports on the core for(Iterator<PortProto> it = corenp.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); Name eName = e.getNameKey(); int wid = eName.busWidth(); if (wid <= 1) continue; for(int i=0; i<wid; i++) { if (eName.subname(i).toString().equals(pa.assocname)) { pi1 = trueBusEnd.get(e); if (pi1 == null) { // make a short bus arc from the port to a bus pin which gets used for connections PortInst pi = ni.findPortInstFromProto(e); PolyBase portPoly = pi.getPoly(); Rectangle2D portRect = portPoly.getBounds2D(); PrimitiveNode busPinProto = Schematics.tech().busPinNode; NodeInst busPin = NodeInst.makeInstance(busPinProto, new EPoint(portRect.getCenterX(), portRect.getCenterY()), busPinProto.getDefWidth(), busPinProto.getDefHeight(), framecell); pi1 = busPin.getOnlyPortInst(); ArcProto busArcProto = Schematics.tech().bus_arc; ArcInst.makeInstance(busArcProto, pi, pi1); trueBusEnd.put(e, pi1); } nameArc = true; break; } } if (pi1 != null) break; } } if (pi1 == null) { PortInst pi = pad.ni.findPortInst(pa.portname); Export.newInstance(pad.ni.getParent(), pi, pa.assocname); continue; } PortInst pi2 = pad.ni.findPortInst(pa.portname); ArcProto ap = Generic.tech().unrouted_arc; ArcInst ai = ArcInst.newInstanceBase(ap, ap.getDefaultLambdaBaseWidth(), pi1, pi2); if (nameArc) { ai.setName(pa.assocname); } else { // give generated name based on the connection String netName = "PADFRAME"; if (pad.exportAssociations != null && pad.exportAssociations.size() > 0) netName += "_" + pad.exportAssociations.get(0).exportName; netName += "_" + pa.assocname; ai.setName(netName); } } } } } } if (view == View.ICON) { // This is a crock until the functionality here can be folded // into CircuitChanges.makeIconViewCommand() // get icon style controls double leadLength = User.getIconGenLeadLength(); double leadSpacing = User.getIconGenLeadSpacing(); // create the new icon cell String iconCellName = framecell.getName() + "{ic}"; Cell iconCell = Cell.makeInstance(destLib, iconCellName); if (iconCell == null) { Job.getUserInterface().showErrorMessage("Cannot create Icon cell " + iconCellName, "Icon creation failed"); return framecell; } iconCell.setWantExpanded(); // determine the size of the "black box" core double ySize = Math.max(Math.max(padPorts.size(), corePorts.size()), 5) * leadSpacing; double xSize = 3 * leadSpacing; // create the "black box" NodeInst bbNi = null; if (User.isIconGenDrawBody()) { bbNi = NodeInst.newInstance(Artwork.tech().openedThickerPolygonNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); if (bbNi == null) return framecell; bbNi.newVar(Artwork.ART_COLOR, new Integer(EGraphics.RED)); EPoint[] points = new EPoint[5]; points[0] = new EPoint(-0.5 * xSize, -0.5 * ySize); points[1] = new EPoint(-0.5 * xSize, 0.5 * ySize); points[2] = new EPoint(0.5 * xSize, 0.5 * ySize); points[3] = new EPoint(0.5 * xSize, -0.5 * ySize); points[4] = new EPoint(-0.5 * xSize, -0.5 * ySize); bbNi.setTrace(points); // put the original cell name on it bbNi.newDisplayVar(Schematics.SCHEM_FUNCTION, framecell.getName()); } // get icon preferences int exportTech = User.getIconGenExportTech(); boolean drawLeads = User.isIconGenDrawLeads(); int exportStyle = User.getIconGenExportStyle(); int exportLocation = User.getIconGenExportLocation(); boolean ad = User.isIconsAlwaysDrawn(); if (coreAllOnOneSide) { List<Export> padTemp = new ArrayList<Export>(); List<Export> coreTemp = new ArrayList<Export>(); for (Export pp : padPorts) { if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } for (Export pp : corePorts) { if (pp == null) { coreTemp.add(pp); continue; } if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } padPorts = padTemp; corePorts = coreTemp; } // place pins around the Black Box int total = 0; int leftSide = padPorts.size(); int rightSide = corePorts.size(); for (Export pp : padPorts) { if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = -xSize / 2; xPos = xBBPos - leadLength; if (leftSide * 2 < rightSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (leftSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 0, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } total = 0; for (Export pp : corePorts) { if (pp == null) { total++; continue; } if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = xSize / 2; xPos = xBBPos + leadLength; if (rightSide * 2 < leftSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (rightSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 1, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } // if no body, leads, or cell center is drawn, and there is only 1 export, add more if (!User.isIconGenDrawBody() && !User.isIconGenDrawLeads() && User.isPlaceCellCenter() && total <= 1) { NodeInst.newInstance(Generic.tech().invisiblePinNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); } // place an icon in the schematic int exampleLocation = User.getIconGenInstanceLocation(); Point2D iconPos = new Point2D.Double(0, 0); Rectangle2D cellBounds = framecell.getBounds(); Rectangle2D iconBounds = iconCell.getBounds(); double halfWidth = iconBounds.getWidth() / 2; double halfHeight = iconBounds.getHeight() / 2; switch (exampleLocation) { case 0: // upper-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMaxY() + halfHeight); break; case 1: // upper-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMaxY() + halfHeight); break; case 2: // lower-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMinY() - halfHeight); break; case 3: // lower-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMinY() - halfHeight); break; } DBMath.gridAlign(iconPos, alignment); double px = iconCell.getBounds().getWidth(); double py = iconCell.getBounds().getHeight(); NodeInst.makeInstance(iconCell, iconPos, px, py, framecell); } return framecell; }
private Cell createPadFrame(String name, View view, Job job) { angle = 0; // first, try to create cell CellName n = CellName.parseName(name); if (n != null && (n.getView() == null || n.getView() == View.UNKNOWN)) { // no view in cell name, append appropriately if (view == null) { name = name + "{lay}"; } else { if (view == View.ICON) { // create a schematic, place icons of pads in it name = name + "{sch}"; } else { name = name + "{" + view.getAbbreviation() + "}"; } } } Cell framecell = Cell.makeInstance(destLib, name); if (framecell == null) { System.out.println("Could not create pad frame Cell: " + name); return null; } List<Export> padPorts = new ArrayList<Export>(); List<Export> corePorts = new ArrayList<Export>(); NodeInst lastni = null; int lastRotate = 0; String lastpadname = null; boolean reversed = false; // cycle through all orderedCommands, doing them for (Object obj : orderedCommands) { // Rotation commands are ordered with respect to Place commands. if (obj instanceof Rotation) { angle = (angle + ((Rotation) obj).angle) % 3600; continue; } if (obj instanceof ReverseDirection) { reversed = !reversed; continue; } // otherwise this is a Place command PlacePad pad = (PlacePad) obj; lineno = pad.lineno; // get cell String cellname = pad.cellname; if (!cellname.endsWith("}")) { if (view != null) cellname = cellname + "{" + view.getAbbreviation() + "}"; } Cell cell = cellLib.findNodeProto(cellname); if (cell == null) { err("Could not create pad Cell: " + cellname); continue; } // if copying cell, copy it into current library if (copycells) { Cell existing = cell; cell = null; for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { List<Cell> fromCells = new ArrayList<Cell>(); fromCells.add(existing); CellChangeJobs.copyRecursively(fromCells, destLib, false, false, false, true, true); for(Iterator<Cell> cIt = destLib.getCells(); cIt.hasNext(); ) { Cell thereCell = cIt.next(); if (thereCell.getName().equals(existing.getName()) && thereCell.getView() == existing.getView()) { cell = thereCell; break; } } if (cell == null) { err("Could not copy in pad Cell " + cellname); continue; } } } // get array alignment for this cell ArrayAlign aa = alignments.get(pad.cellname); if (aa == null) { err("No port alignment for cell " + pad.cellname); continue; } int gapx = 0, gapy = 0; double centerX = 0, centerY = 0; if (lastni != null) { // get info on last nodeinst created ArrayAlign lastaa = alignments.get(lastpadname); // get previous node's outport - use it to place this nodeinst PortProto pp = (lastni.getProto()).findPortProto(lastaa.outport); if (pp == null) { err("no port called '" + lastaa.outport + "' on " + lastni); continue; } Poly poly = (lastni.findPortInstFromProto(pp)).getPoly(); centerX = poly.getCenterX(); centerY = poly.getCenterY(); } Point2D pointCenter = new Point2D.Double(centerX, centerY); boolean flipLR = false; boolean flipUD = false; if (reversed) flipUD = true; Orientation orient = Orientation.fromJava(angle, flipLR, flipUD); NodeInst ni = NodeInst.makeInstance(cell, pointCenter, cell.getDefWidth(), cell.getDefHeight(), framecell, orient, null, 0); if (ni == null) { err("problem creating" + cell + " instance"); continue; } if (lastni != null) { int gap = pad.gap; if (reversed) gap = -gap; switch (lastRotate) { case 0: gapx = gap; gapy = 0; break; case 900: gapx = 0; gapy = gap; break; case 1800: gapx = -gap; gapy = 0; break; case 2700: gapx = 0; gapy = -gap; break; } PortProto inport = cell.findPortProto(aa.inport); if (inport == null) { err("No port called '" + aa.inport + "' on " + cell); continue; } Poly poly = ni.findPortInstFromProto(inport).getPoly(); double tempx = centerX - poly.getCenterX() + gapx; double tempy = centerY - poly.getCenterY() + gapy; ni.move(tempx, tempy); } double dx = 0, dy = 0; if (pad.locx != null) dx = pad.locx.doubleValue() - ni.getAnchorCenterX(); if (pad.locy != null) dy = pad.locy.doubleValue() - ni.getAnchorCenterY(); ni.move(dx, dy); // create exports // get export for this cell, if any if (pad.exportsname != null) { PadExports pe = exports.get(pad.cellname); if (pe != null) { // pad export Export pppad = cell.findExport(pe.padname); if (pppad == null) { err("no port called '" + pe.padname + "' on Cell " + cell.noLibDescribe()); } else { pppad = Export.newInstance(framecell, ni.findPortInstFromProto(pppad), pad.exportsname); if (pppad == null) err("Creating export " + pad.exportsname); else { TextDescriptor td = pppad.getTextDescriptor(Export.EXPORT_NAME); pppad.setTextDescriptor(Export.EXPORT_NAME, td.withAbsSize(14)); padPorts.add(pppad); } } // core export if (pe.corename != null) { Export ppcore = cell.findExport(pe.corename); if (ppcore == null) { err("no port called '" + pe.corename + "' on Cell " + cell.noLibDescribe()); } else { ppcore = Export.newInstance(framecell, ni.findPortInstFromProto(ppcore), "core_" + pad.exportsname); if (ppcore == null) err("Creating export core_" + pad.exportsname); else { TextDescriptor td = ppcore.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(ppcore); ppcore.setTextDescriptor(Export.EXPORT_NAME, td); } } } else { corePorts.add(null); } } } // create exports from export pad=name command for (ExportAssociate ea : pad.exportAssociations) { Export pp = cell.findExport(ea.padportName); if (pp == null) { err("no port called '" + ea.padportName + "' on Cell " + cell.noLibDescribe()); } else { pp = Export.newInstance(framecell, ni.findPortInstFromProto(pp), ea.exportName); if (pp == null) err("Creating export "+ea.exportName); else { TextDescriptor td = pp.getTextDescriptor(Export.EXPORT_NAME).withAbsSize(14); corePorts.add(pp); pp.setTextDescriptor(Export.EXPORT_NAME, td); } } } lastni = ni; lastRotate = angle; lastpadname = pad.cellname; pad.ni = ni; } // auto stitch everything AutoStitch.runAutoStitch(framecell, null, null, job, null, null, true, false, false); if (corename != null) { // first, try to create cell String corenameview = corename; CellName coreName = CellName.parseName(corename); if (view != null && coreName.getView() == View.UNKNOWN) { corenameview = corename + "{" + view.getAbbreviation() + "}"; } Cell corenp = destLib.findNodeProto(corenameview); if (corenp == null) { System.out.println("Line " + lineno + ": cannot find core cell " + corenameview); } else { Rectangle2D bounds = framecell.getBounds(); Point2D center = new Point2D.Double(bounds.getCenterX(), bounds.getCenterY()); DBMath.gridAlign(center, alignment); NodeInst ni = NodeInst.makeInstance(corenp, center, corenp.getDefWidth(), corenp.getDefHeight(), framecell); Map<Export,PortInst> trueBusEnd = new HashMap<Export,PortInst>(); for (Object obj : orderedCommands) { if (obj instanceof PlacePad) { PlacePad pad = (PlacePad) obj; for (PortAssociate pa : pad.associations) { if (pad.ni == null) continue; boolean nameArc = false; PortInst pi1 = null; PortProto corepp = corenp.findPortProto(pa.assocname); if (corepp != null) pi1 = ni.findPortInstFromProto(corepp); if (pi1 == null) { // see if there are bus ports on the core for(Iterator<PortProto> it = corenp.getPorts(); it.hasNext(); ) { Export e = (Export)it.next(); Name eName = e.getNameKey(); int wid = eName.busWidth(); if (wid <= 1) continue; for(int i=0; i<wid; i++) { if (eName.subname(i).toString().equals(pa.assocname)) { pi1 = trueBusEnd.get(e); if (pi1 == null) { // make a short bus arc from the port to a bus pin which gets used for connections PortInst pi = ni.findPortInstFromProto(e); PolyBase portPoly = pi.getPoly(); Rectangle2D portRect = portPoly.getBounds2D(); PrimitiveNode busPinProto = Schematics.tech().busPinNode; NodeInst busPin = NodeInst.makeInstance(busPinProto, new EPoint(portRect.getCenterX(), portRect.getCenterY()), busPinProto.getDefWidth(), busPinProto.getDefHeight(), framecell); pi1 = busPin.getOnlyPortInst(); ArcProto busArcProto = Schematics.tech().bus_arc; ArcInst.makeInstance(busArcProto, pi, pi1); trueBusEnd.put(e, pi1); } nameArc = true; break; } } if (pi1 != null) break; } } if (pi1 == null) { PortInst pi = pad.ni.findPortInst(pa.portname); Export.newInstance(pad.ni.getParent(), pi, pa.assocname); continue; } PortInst pi2 = pad.ni.findPortInst(pa.portname); ArcProto ap = Generic.tech().unrouted_arc; ArcInst ai = ArcInst.newInstanceBase(ap, ap.getDefaultLambdaBaseWidth(), pi1, pi2); if (nameArc) { ai.setName(pa.assocname); } else { // give generated name based on the connection String netName = "PADFRAME"; if (pad.exportAssociations != null && pad.exportAssociations.size() > 0) netName += "_" + pad.exportAssociations.get(0).exportName; netName += "_" + pa.assocname; ai.setName(netName); } } } } } } if (view == View.ICON) { // This is a crock until the functionality here can be folded // into CircuitChanges.makeIconViewCommand() // get icon style controls double leadLength = User.getIconGenLeadLength(); double leadSpacing = User.getIconGenLeadSpacing(); // create the new icon cell String iconCellName = framecell.getName() + "{ic}"; Cell iconCell = Cell.makeInstance(destLib, iconCellName); if (iconCell == null) { Job.getUserInterface().showErrorMessage("Cannot create Icon cell " + iconCellName, "Icon creation failed"); return framecell; } iconCell.setWantExpanded(); // determine the size of the "black box" core double ySize = Math.max(Math.max(padPorts.size(), corePorts.size()), 5) * leadSpacing; double xSize = 3 * leadSpacing; // create the "black box" NodeInst bbNi = null; if (User.isIconGenDrawBody()) { bbNi = NodeInst.newInstance(Artwork.tech().openedThickerPolygonNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); if (bbNi == null) return framecell; bbNi.newVar(Artwork.ART_COLOR, new Integer(EGraphics.RED)); EPoint[] points = new EPoint[5]; points[0] = new EPoint(-0.5 * xSize, -0.5 * ySize); points[1] = new EPoint(-0.5 * xSize, 0.5 * ySize); points[2] = new EPoint(0.5 * xSize, 0.5 * ySize); points[3] = new EPoint(0.5 * xSize, -0.5 * ySize); points[4] = new EPoint(-0.5 * xSize, -0.5 * ySize); bbNi.setTrace(points); // put the original cell name on it bbNi.newDisplayVar(Schematics.SCHEM_FUNCTION, framecell.getName()); } // get icon preferences int exportTech = User.getIconGenExportTech(); boolean drawLeads = User.isIconGenDrawLeads(); int exportStyle = User.getIconGenExportStyle(); int exportLocation = User.getIconGenExportLocation(); boolean ad = User.isIconsAlwaysDrawn(); if (coreAllOnOneSide) { List<Export> padTemp = new ArrayList<Export>(); List<Export> coreTemp = new ArrayList<Export>(); for (Export pp : padPorts) { if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } for (Export pp : corePorts) { if (pp == null) { coreTemp.add(pp); continue; } if (pp.getName().startsWith("core_")) coreTemp.add(pp); else padTemp.add(pp); } padPorts = padTemp; corePorts = coreTemp; } // place pins around the Black Box int total = 0; int leftSide = padPorts.size(); int rightSide = corePorts.size(); for (Export pp : padPorts) { if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = -xSize / 2; xPos = xBBPos - leadLength; if (leftSide * 2 < rightSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (leftSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 0, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } total = 0; for (Export pp : corePorts) { if (pp == null) { total++; continue; } if (pp.isBodyOnly()) continue; // determine location of the port double spacing = leadSpacing; double xPos = 0, yPos = 0; double xBBPos = 0, yBBPos = 0; xBBPos = xSize / 2; xPos = xBBPos + leadLength; if (rightSide * 2 < leftSide) spacing = leadSpacing * 2; yBBPos = yPos = ySize / 2 - ((ySize - (rightSide - 1) * spacing) / 2 + total * spacing); int rotation = ViewChanges.iconTextRotation(pp, User.getIconGenInputRot(), User.getIconGenOutputRot(), User.getIconGenBidirRot(), User.getIconGenPowerRot(), User.getIconGenGroundRot(), User.getIconGenClockRot()); if (ViewChanges.makeIconExport(pp, 1, xPos, yPos, xBBPos, yBBPos, iconCell, exportTech, drawLeads, exportStyle, exportLocation, rotation, ad)) total++; } // if no body, leads, or cell center is drawn, and there is only 1 export, add more if (!User.isIconGenDrawBody() && !User.isIconGenDrawLeads() && User.isPlaceCellCenter() && total <= 1) { NodeInst.newInstance(Generic.tech().invisiblePinNode, new Point2D.Double(0, 0), xSize, ySize, iconCell); } // place an icon in the schematic int exampleLocation = User.getIconGenInstanceLocation(); Point2D iconPos = new Point2D.Double(0, 0); Rectangle2D cellBounds = framecell.getBounds(); Rectangle2D iconBounds = iconCell.getBounds(); double halfWidth = iconBounds.getWidth() / 2; double halfHeight = iconBounds.getHeight() / 2; switch (exampleLocation) { case 0: // upper-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMaxY() + halfHeight); break; case 1: // upper-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMaxY() + halfHeight); break; case 2: // lower-right iconPos.setLocation(cellBounds.getMaxX() + halfWidth, cellBounds.getMinY() - halfHeight); break; case 3: // lower-left iconPos.setLocation(cellBounds.getMinX() - halfWidth, cellBounds.getMinY() - halfHeight); break; } DBMath.gridAlign(iconPos, alignment); double px = iconCell.getBounds().getWidth(); double py = iconCell.getBounds().getHeight(); NodeInst.makeInstance(iconCell, iconPos, px, py, framecell); } return framecell; }
diff --git a/xslthl/src/net/sf/xslthl/highlighters/StringHighlighter.java b/xslthl/src/net/sf/xslthl/highlighters/StringHighlighter.java index 4cb367c..0f2eba3 100644 --- a/xslthl/src/net/sf/xslthl/highlighters/StringHighlighter.java +++ b/xslthl/src/net/sf/xslthl/highlighters/StringHighlighter.java @@ -1,144 +1,145 @@ /* * xslthl - XSLT Syntax Highlighting * https://sourceforge.net/projects/xslthl/ * Copyright (C) 2005-2008 Michal Molhanec, Jirka Kosek, Michiel Hendriks * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * * Michal Molhanec <mol1111 at users.sourceforge.net> * Jirka Kosek <kosek at users.sourceforge.net> * Michiel Hendriks <elmuerte at users.sourceforge.net> */ package net.sf.xslthl.highlighters; import java.util.List; import net.sf.xslthl.Block; import net.sf.xslthl.CharIter; import net.sf.xslthl.Highlighter; import net.sf.xslthl.HighlighterConfigurationException; import net.sf.xslthl.Params; /** * Recognizes strings. Accepted parameters: * <dl> * <dt>string</dt> * <dd>How the string starts. <b>Required.</b></dd> * <dt>endString</dt> * <dd>How the string ends. If not present the start value is used.</dd> * <dt>escape</dt> * <dd>Character to use to escape characters. Optional.</dd> * <dt>doubleEscapes</dt> * <dd>When present the double usage of start is considered to be an escaped * start (used in Pascal). Optional.</dd> * <dt>spanNewLines</dt> * <dd>When present strings can span newlines, otherwise a newline breaks the * string parsing.</dd> * </dl> */ public class StringHighlighter extends Highlighter { /** * The start token and the escape token. */ private String start, end, escape; /** * If set the double occurance of start escapes it. */ private boolean doubleEscapes; /** * If set newlines are ignored in string parsing. */ private boolean spansNewLines; /* * (non-Javadoc) * * @see net.sf.xslthl.Highlighter#init(net.sf.xslthl.Params) */ @Override public void init(Params params) throws HighlighterConfigurationException { super.init(params); start = params.getParam("string"); end = params.getParam("endString", start); escape = params.getParam("escape"); doubleEscapes = params.isSet("doubleEscapes"); spansNewLines = params.isSet("spanNewLines"); if (start == null || start.length() == 0) { throw new HighlighterConfigurationException( "Required parameter 'start' is not set."); } } /* * (non-Javadoc) * * @see net.sf.xslthl.Highlighter#startsWith(net.sf.xslthl.CharIter) */ @Override public boolean startsWith(CharIter in) { if (in.startsWith(start)) { return true; } return false; } /* * (non-Javadoc) * * @see net.sf.xslthl.Highlighter#highlight(net.sf.xslthl.CharIter, * java.util.List) */ @Override public boolean highlight(CharIter in, List<Block> out) { in.moveNext(start.length()); // skip start boolean wasEscape = false; while (!in.finished()) { if (!spansNewLines && isNewLine(in.current())) { break; } if (in.startsWith(end) && !wasEscape) { if (doubleEscapes && in.startsWith(end, end.length())) { in.moveNext(); } else { + in.moveNext(end.length()-1); break; } } else if (escape != null && in.startsWith(escape) && !wasEscape) { wasEscape = true; } else { wasEscape = false; } in.moveNext(); } if (!in.finished()) { in.moveNext(); } out.add(in.markedToStyledBlock(styleName)); return true; } /* * (non-Javadoc) * * @see net.sf.xslthl.Highlighter#getDefaultStyle() */ @Override public String getDefaultStyle() { return "string"; } }
true
true
public boolean highlight(CharIter in, List<Block> out) { in.moveNext(start.length()); // skip start boolean wasEscape = false; while (!in.finished()) { if (!spansNewLines && isNewLine(in.current())) { break; } if (in.startsWith(end) && !wasEscape) { if (doubleEscapes && in.startsWith(end, end.length())) { in.moveNext(); } else { break; } } else if (escape != null && in.startsWith(escape) && !wasEscape) { wasEscape = true; } else { wasEscape = false; } in.moveNext(); } if (!in.finished()) { in.moveNext(); } out.add(in.markedToStyledBlock(styleName)); return true; }
public boolean highlight(CharIter in, List<Block> out) { in.moveNext(start.length()); // skip start boolean wasEscape = false; while (!in.finished()) { if (!spansNewLines && isNewLine(in.current())) { break; } if (in.startsWith(end) && !wasEscape) { if (doubleEscapes && in.startsWith(end, end.length())) { in.moveNext(); } else { in.moveNext(end.length()-1); break; } } else if (escape != null && in.startsWith(escape) && !wasEscape) { wasEscape = true; } else { wasEscape = false; } in.moveNext(); } if (!in.finished()) { in.moveNext(); } out.add(in.markedToStyledBlock(styleName)); return true; }
diff --git a/htroot/Messages_p.java b/htroot/Messages_p.java index 9ce225507..a562c3ae6 100644 --- a/htroot/Messages_p.java +++ b/htroot/Messages_p.java @@ -1,135 +1,135 @@ // Messages_p.java // ----------------------- // part of the AnomicHTTPD caching proxy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // last major change: 28.06.2003 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. // You must compile this file with // javac -classpath .:../Classes Message.java // if the shell's current path is HTROOT import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import de.anomic.data.messageBoard; import de.anomic.http.httpHeader; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverFileUtils; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; public class Messages_p { private static SimpleDateFormat SimpleFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static String dateString(Date date) { return SimpleFormatter.format(date); } public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String action = ((post == null) ? "list" : post.get("action", "list")); String messages = ""; messageBoard.entry message; // first reset notification File notifierSource = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifierInactive.gif"); File notifierDest = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifier.gif"); try {serverFileUtils.copy(notifierSource, notifierDest);} catch (IOException e) {}; if (action.equals("delete")) { String key = post.get("object",""); switchboard.messageDB.remove(key); action = "list"; } if (action.equals("list")) { messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">" + "<tr class=\"MenuHeader\"><td>Date</td><td>From</td><td>To</td><td>Subject</td><td>Action</td></tr>"; try { Iterator i = switchboard.messageDB.keys("remote", true); String key; boolean dark = true; while (i.hasNext()) { key = (String) i.next(); message = switchboard.messageDB.read(key); messages += "<tr class=\"TableCell" + ((dark) ? "Dark" : "Light") + "\">"; dark = !dark; messages += "<td>" + dateString(message.date()) + "</td>"; messages += "<td>" + message.author() + "</td>"; messages += "<td>" + message.recipient() + "</td>"; messages += "<td>" + message.subject() + "</td>"; messages += "<td>" + "<a href=\"Messages_p.html?action=view&object=" + key + "\">view</a>&nbsp;/&nbsp;" + "<a href=\"MessageSend_p.html?hash=" + message.authorHash() + "&subject=Re: " + message.subject() + "\">reply</a>&nbsp;/&nbsp;" + "<a href=\"Messages_p.html?action=delete&object=" + key + "\">delete</a>" + "</td>"; messages += "</tr>"; } messages += "</table>"; } catch (IOException e) { - messages += "IO Error reading message Table: " + e.getMessage(); + messages += "I/O error reading message table: " + e.getMessage(); } } if (action.equals("view")) { String key = post.get("object",""); message = switchboard.messageDB.read(key); messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">"; messages += "<tr><td class=\"MenuHeader\">From:</td><td class=\"MessageBackground\">" + message.author() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">To:</td><td class=\"MessageBackground\">" + message.recipient() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Send Date:</td><td class=\"MessageBackground\">" + dateString(message.date()) + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Subject:</td><td class=\"MessageBackground\">" + message.subject() + "</td></tr>"; messages += "<tr><td class=\"MessageBackground\" colspan=\"2\">" + new String(message.message()) + "</td></tr>"; messages += "</table>"; } prop.put("messages", messages); // return rewrite properties return prop; } }
true
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String action = ((post == null) ? "list" : post.get("action", "list")); String messages = ""; messageBoard.entry message; // first reset notification File notifierSource = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifierInactive.gif"); File notifierDest = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifier.gif"); try {serverFileUtils.copy(notifierSource, notifierDest);} catch (IOException e) {}; if (action.equals("delete")) { String key = post.get("object",""); switchboard.messageDB.remove(key); action = "list"; } if (action.equals("list")) { messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">" + "<tr class=\"MenuHeader\"><td>Date</td><td>From</td><td>To</td><td>Subject</td><td>Action</td></tr>"; try { Iterator i = switchboard.messageDB.keys("remote", true); String key; boolean dark = true; while (i.hasNext()) { key = (String) i.next(); message = switchboard.messageDB.read(key); messages += "<tr class=\"TableCell" + ((dark) ? "Dark" : "Light") + "\">"; dark = !dark; messages += "<td>" + dateString(message.date()) + "</td>"; messages += "<td>" + message.author() + "</td>"; messages += "<td>" + message.recipient() + "</td>"; messages += "<td>" + message.subject() + "</td>"; messages += "<td>" + "<a href=\"Messages_p.html?action=view&object=" + key + "\">view</a>&nbsp;/&nbsp;" + "<a href=\"MessageSend_p.html?hash=" + message.authorHash() + "&subject=Re: " + message.subject() + "\">reply</a>&nbsp;/&nbsp;" + "<a href=\"Messages_p.html?action=delete&object=" + key + "\">delete</a>" + "</td>"; messages += "</tr>"; } messages += "</table>"; } catch (IOException e) { messages += "IO Error reading message Table: " + e.getMessage(); } } if (action.equals("view")) { String key = post.get("object",""); message = switchboard.messageDB.read(key); messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">"; messages += "<tr><td class=\"MenuHeader\">From:</td><td class=\"MessageBackground\">" + message.author() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">To:</td><td class=\"MessageBackground\">" + message.recipient() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Send Date:</td><td class=\"MessageBackground\">" + dateString(message.date()) + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Subject:</td><td class=\"MessageBackground\">" + message.subject() + "</td></tr>"; messages += "<tr><td class=\"MessageBackground\" colspan=\"2\">" + new String(message.message()) + "</td></tr>"; messages += "</table>"; } prop.put("messages", messages); // return rewrite properties return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { plasmaSwitchboard switchboard = (plasmaSwitchboard) env; serverObjects prop = new serverObjects(); String action = ((post == null) ? "list" : post.get("action", "list")); String messages = ""; messageBoard.entry message; // first reset notification File notifierSource = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifierInactive.gif"); File notifierDest = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot") + "/env/grafics/notifier.gif"); try {serverFileUtils.copy(notifierSource, notifierDest);} catch (IOException e) {}; if (action.equals("delete")) { String key = post.get("object",""); switchboard.messageDB.remove(key); action = "list"; } if (action.equals("list")) { messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">" + "<tr class=\"MenuHeader\"><td>Date</td><td>From</td><td>To</td><td>Subject</td><td>Action</td></tr>"; try { Iterator i = switchboard.messageDB.keys("remote", true); String key; boolean dark = true; while (i.hasNext()) { key = (String) i.next(); message = switchboard.messageDB.read(key); messages += "<tr class=\"TableCell" + ((dark) ? "Dark" : "Light") + "\">"; dark = !dark; messages += "<td>" + dateString(message.date()) + "</td>"; messages += "<td>" + message.author() + "</td>"; messages += "<td>" + message.recipient() + "</td>"; messages += "<td>" + message.subject() + "</td>"; messages += "<td>" + "<a href=\"Messages_p.html?action=view&object=" + key + "\">view</a>&nbsp;/&nbsp;" + "<a href=\"MessageSend_p.html?hash=" + message.authorHash() + "&subject=Re: " + message.subject() + "\">reply</a>&nbsp;/&nbsp;" + "<a href=\"Messages_p.html?action=delete&object=" + key + "\">delete</a>" + "</td>"; messages += "</tr>"; } messages += "</table>"; } catch (IOException e) { messages += "I/O error reading message table: " + e.getMessage(); } } if (action.equals("view")) { String key = post.get("object",""); message = switchboard.messageDB.read(key); messages += "<table border=\"0\" cellpadding=\"2\" cellspacing=\"1\">"; messages += "<tr><td class=\"MenuHeader\">From:</td><td class=\"MessageBackground\">" + message.author() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">To:</td><td class=\"MessageBackground\">" + message.recipient() + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Send Date:</td><td class=\"MessageBackground\">" + dateString(message.date()) + "</td></tr>"; messages += "<tr><td class=\"MenuHeader\">Subject:</td><td class=\"MessageBackground\">" + message.subject() + "</td></tr>"; messages += "<tr><td class=\"MessageBackground\" colspan=\"2\">" + new String(message.message()) + "</td></tr>"; messages += "</table>"; } prop.put("messages", messages); // return rewrite properties return prop; }
diff --git a/src/graindcafe/tribu/Tribu.java b/src/graindcafe/tribu/Tribu.java index f095375..ff3ef7f 100644 --- a/src/graindcafe/tribu/Tribu.java +++ b/src/graindcafe/tribu/Tribu.java @@ -1,792 +1,793 @@ package graindcafe.tribu; import graindcafe.tribu.BlockTracer.BlockTrace; import graindcafe.tribu.Configuration.Constants; import graindcafe.tribu.Configuration.TribuConfig; import graindcafe.tribu.Executors.CmdDspawn; import graindcafe.tribu.Executors.CmdIspawn; import graindcafe.tribu.Executors.CmdTribu; import graindcafe.tribu.Executors.CmdZspawn; import graindcafe.tribu.Inventory.TribuInventory; import graindcafe.tribu.Inventory.TribuTempInventory; import graindcafe.tribu.Level.LevelFileLoader; import graindcafe.tribu.Level.LevelSelector; import graindcafe.tribu.Level.TribuLevel; import graindcafe.tribu.Listeners.TribuBlockListener; import graindcafe.tribu.Listeners.TribuEntityListener; import graindcafe.tribu.Listeners.TribuPlayerListener; import graindcafe.tribu.Listeners.TribuWorldListener; import graindcafe.tribu.Signs.TollSign; import graindcafe.tribu.TribuZombie.EntityTribuZombie; import java.io.File; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Logger; import me.graindcafe.gls.DefaultLanguage; import me.graindcafe.gls.Language; import net.minecraft.server.EntityTypes; import net.minecraft.server.EntityZombie; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Villager; import org.bukkit.entity.Wolf; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; public class Tribu extends JavaPlugin { public static String getExceptionMessage(Exception e) { String message = e.getLocalizedMessage() + "\n"; for (StackTraceElement st : e.getStackTrace()) message += "[" + st.getFileName() + ":" + st.getLineNumber() + "] " + st.getClassName() + "->" + st.getMethodName() + "\n"; return message; } private int aliveCount; private TribuBlockListener blockListener; private BlockTrace blockTrace; private TribuEntityListener entityListener; public TribuInventory inventorySave; private boolean isRunning; private Language language; private TribuLevel level; private LevelFileLoader levelLoader; private LevelSelector levelSelector; private Logger log; private TribuPlayerListener playerListener; private HashMap<Player, PlayerStats> players; private HashMap<Player,Location> spawnPoint; private Random rnd; private LinkedList<PlayerStats> sortedStats; private TribuSpawner spawner; private SpawnTimer spawnTimer; private HashMap<Player, TribuTempInventory> tempInventories; private boolean waitingForPlayers = false; private WaveStarter waveStarter; private TribuWorldListener worldListener; private TribuConfig config; public void addPlayer(Player player) { if (player != null && !players.containsKey(player)) { if (config.PlayersStoreInventory) { saveSetTribuInventory(player); } PlayerStats stats = new PlayerStats(player); players.put(player, stats); sortedStats.add(stats); if (isWaitingForPlayers()) { startRunning(); setWaitingForPlayers(false); } else if (getLevel() != null && isRunning) { player.teleport(level.getDeathSpawn()); messagePlayer(player,language.get("Message.GameInProgress")); messagePlayer(player,language.get("Message.PlayerDied")); deadPeople.put(player,null); } } } public void saveSetTribuInventory(Player player) { inventorySave.addInventory(player); player.getInventory().clear(); player.getInventory().setArmorContents(null); } public void addDefaultPackages() { if (level != null && this.config.DefaultPackages != null) for (Package pck : this.config.DefaultPackages) { level.addPackage(pck); } } public void checkAliveCount() { // log.info("checking alive count " + aliveCount); int alive = players.size() - deadPeople.size(); if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used. deadPeople.clear(); stopRunning(); messagePlayers(language.get("Message.ZombieHavePrevailed")); messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber()))); if (getPlayersCount() != 0) getLevelSelector().startVote(Constants.VoteDelay); } } public int getAliveCount() { return aliveCount; } public BlockTrace getBlockTrace() { return blockTrace; } public TribuLevel getLevel() { return level; } public LevelFileLoader getLevelLoader() { return levelLoader; } public LevelSelector getLevelSelector() { return levelSelector; } public String getLocale(String key) { /* * String r = language.get(key); if (r == null) { LogWarning(key + * " not found"); r = ChatColor.RED + * "An error occured while getting this message"; } return r; */ return language.get(key); } public Set<Player> getPlayers() { return this.players.keySet(); } public int getPlayersCount() { return this.players.size(); } public Player getRandomPlayer() { return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer(); } public LinkedList<PlayerStats> getSortedStats() { Collections.sort(this.sortedStats); /* * Iterator<PlayerStats> i=this.sortedStats.iterator(); while * (i.hasNext()) { PlayerStats ps = i.next(); * LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); } */ return this.sortedStats; } public TribuSpawner getSpawner() { return spawner; } public SpawnTimer getSpawnTimer() { return spawnTimer; } public boolean isInsideLevel(Location loc) { if (isRunning && level != null) return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone); else return false; } public PlayerStats getStats(Player player) { return players.get(player); } public WaveStarter getWaveStarter() { return waveStarter; } private void initPluginMode() { if (config.PluginModeServerExclusive) { for (Player p : this.getServer().getOnlinePlayers()) this.addPlayer(p); } if(config.PluginModeWorldExclusive) { for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) { this.addPlayer(d); } } if (config.PluginModeDefaultLevel != "") setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel)); if (config.PluginModeAutoStart) startRunning(); } public void reloadConf() { this.reloadConfig(); this.loadCustomConf(); this.initPluginMode(); } public void loadCustomConf() { TribuLevel level=this.getLevel(); if (level == null) return; File worldFile = null, levelFile = null, worldDir, levelDir; worldDir = new File(Constants.perWorldFolder); levelDir = new File(Constants.perLevelFolder); String levelName = level.getName() + ".yml"; String worldName = level.getInitialSpawn().getWorld().getName() + ".yml"; if (!levelDir.exists()) levelDir.mkdirs(); if (!worldDir.exists()) worldDir.mkdirs(); for (File file : levelDir.listFiles()) { if (file.getName().equalsIgnoreCase(levelName)) { levelFile = file; break; } } for (File file : worldDir.listFiles()) { if (file.getName().equalsIgnoreCase(worldName)) { worldFile = file; break; } } if(levelFile!=null) if(worldFile != null) this.config=new TribuConfig(levelFile,new TribuConfig(worldFile)); else this.config=new TribuConfig(levelFile); else this.config=new TribuConfig(); /* try { config.set("DefaultPackages", null); config.load(Constants.configFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } if (worldFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } if (levelFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } */ } private void initLanguage() { DefaultLanguage.setAuthor("Graindcafe"); DefaultLanguage.setName("English"); DefaultLanguage.setVersion(Constants.LanguageFileVersion); DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar); DefaultLanguage.setLocales(new HashMap<String, String>() { private static final long serialVersionUID = 9166935722459443352L; { put("File.DefaultLanguageFile", "# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n"); put("File.LanguageFileComplete", "# Your language file is complete\n"); put("File.TranslationsToDo", "# Translations to do in this language file\n"); put("Sign.Buy", "Buy"); put("Sign.ToggleSpawner", "Spawn's switch"); put("Sign.Spawner", "Zombie Spawner"); put("Sign.HighscoreNames", "Top Names"); put("Sign.HighscorePoints", "Top Points"); put("Sign.TollSign", "Pay"); put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : "); put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item"); put("Message.ZombieSpawnList", ChatColor.GREEN + "%s"); put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command"); put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!"); put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded"); put("Message.InvalidVote", ChatColor.RED + "Invalid vote"); put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote"); put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time"); put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully"); put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level"); put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later"); put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later"); put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level"); put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,"); put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,"); put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn"); put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set."); put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn"); put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set."); put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level."); put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful"); put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created"); put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level."); put("Message.PackageCreated", ChatColor.RED + "Package created successfully"); put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully."); put("Message.Levels", ChatColor.GREEN + "Levels: %s"); put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s"); put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in."); put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!"); put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!"); put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added"); put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed"); put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name"); put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s"); put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item..."); put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $"); put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!"); put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s"); put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round"); put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!"); put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s"); put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies."); put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies."); put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added."); put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed."); put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it."); put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it."); put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded."); put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level."); put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package."); put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first."); put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id."); put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid."); put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created."); put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened."); put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed."); put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed."); put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted."); put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added."); put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added."); put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s."); put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified"); put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns."); put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry."); put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in."); put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen"); put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,"); put("Broadcast.Type", ChatColor.DARK_AQUA + "Type "); put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s"); put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds"); put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health"); put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds."); put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete"); put("Info.LevelFound", ChatColor.YELLOW + "%s levels found"); put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20"); put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu"); put("Info.LevelSaved", ChatColor.GREEN + "Level saved"); put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s."); put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist"); put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded."); put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level"); put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console"); put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete"); put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated"); put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing"); put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags."); put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'."); put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn."); put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !"); put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version"); put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist"); put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s"); put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s"); put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s"); put("Severe.Exception", ChatColor.RED + "Exception: %s"); put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)"); put("Message.PlayerDied",ChatColor.RED + "You are dead."); + put("Message.PlayerRevive",ChatColor.GREEN + "You have been revived."); } }); language = Language.init(log, config.PluginModeLanguage); Constants.MessageMoneyPoints = language.get("Message.MoneyPoints"); Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList"); } public boolean isAlive(Player player) { return players.get(player).isalive(); } public TribuConfig config() { return config; } public boolean isPlaying(Player p) { return players.containsKey(p); } public boolean isRunning() { return isRunning; } public void keepTempInv(Player p, ItemStack[] items) { // log.info("Keep " + items.length + " items for " + // p.getDisplayName()); tempInventories.put(p, new TribuTempInventory(p, items)); } public void LogInfo(String message) { log.info("[Tribu] " + message); } public void LogSevere(String message) { log.severe("[Tribu] " + message); } public void LogWarning(String message) { log.warning("[Tribu] " + message); } @Override public void onDisable() { for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe(player + language.get("Severe.PlayerDidntGetInvBack")); } } players.clear(); sortedStats.clear(); stopRunning(); LogInfo(language.get("Info.Disable")); } @Override public void onEnable() { log = Logger.getLogger("Minecraft"); rnd = new Random(); Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar); this.config=new TribuConfig(); initLanguage(); try { @SuppressWarnings("rawtypes") Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE }; Method a = EntityTypes.class.getDeclaredMethod("a", args); a.setAccessible(true); a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893); a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893); } catch (Exception e) { e.printStackTrace(); setEnabled(false); return; } isRunning = false; aliveCount = 0; level = null; blockTrace = new BlockTrace(); tempInventories = new HashMap<Player, TribuTempInventory>(); inventorySave = new TribuInventory(); players = new HashMap<Player, PlayerStats>(); spawnPoint=new HashMap<Player,Location>(); sortedStats = new LinkedList<PlayerStats>(); levelLoader = new LevelFileLoader(this); levelSelector = new LevelSelector(this); spawner = new TribuSpawner(this); spawnTimer = new SpawnTimer(this); waveStarter = new WaveStarter(this); // Create listeners playerListener = new TribuPlayerListener(this); entityListener = new TribuEntityListener(this); blockListener = new TribuBlockListener(this); worldListener = new TribuWorldListener(this); this.initPluginMode(); this.loadCustomConf(); getServer().getPluginManager().registerEvents(playerListener, this); getServer().getPluginManager().registerEvents(entityListener, this); getServer().getPluginManager().registerEvents(blockListener, this); getServer().getPluginManager().registerEvents(worldListener, this); getCommand("dspawn").setExecutor(new CmdDspawn(this)); getCommand("zspawn").setExecutor(new CmdZspawn(this)); getCommand("ispawn").setExecutor(new CmdIspawn(this)); getCommand("tribu").setExecutor(new CmdTribu(this)); LogInfo(language.get("Info.Enable")); } public void resetedSpawnAdd(Player p,Location point) { spawnPoint.put(p, point); } public void removePlayer(Player player) { if (player != null && players.containsKey(player)) { if (isAlive(player)) { aliveCount--; } sortedStats.remove(players.get(player)); inventorySave.restoreInventory(player); players.remove(player); if(player.isOnline() && spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } // check alive AFTER player remove checkAliveCount(); if (!player.isDead()) restoreInventory(player); } } public void restoreInventory(Player p) { // log.info("Restore items for " + p.getDisplayName()); inventorySave.restoreInventory(p); } public void restoreTempInv(Player p) { // log.info("Restore items for " + p.getDisplayName()); if (tempInventories.containsKey(p)) tempInventories.remove(p).restore(); } public void revivePlayer(Player player) { if(spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } players.get(player).revive(); if (config.WaveStartHealPlayers) player.setHealth(20); restoreTempInv(player); aliveCount++; } public void revivePlayers(boolean teleportAll) { aliveCount = 0; for (Player player : players.keySet()) { revivePlayer(player); if (isRunning && level != null && (teleportAll || !isAlive(player))) { player.teleport(level.getInitialSpawn()); } } } public void setDead(Player player) { if (players.containsKey(player)) { if (isAlive(player)) { aliveCount--; PlayerStats p = players.get(player); p.resetMoney(); p.subtractmoney(config.StatsOnPlayerDeathMoney); p.subtractPoints(config.StatsOnPlayerDeathPoints); p.msgStats(); messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died."); /* * Set<Entry<Player, PlayerStats>> stats = players.entrySet(); * for (Entry<Player, PlayerStats> stat : stats) { * stat.getValue().subtractPoints(50); * stat.getValue().resetMoney(); stat.getValue().msgStats(); } */ } deadPeople.put(player,null); players.get(player).kill(); if (getLevel() != null && isRunning) { checkAliveCount(); } } } public void setLevel(TribuLevel level) { this.level = level; this.loadCustomConf(); } public boolean startRunning() { if (!isRunning && getLevel() != null) { if (players.isEmpty()) { setWaitingForPlayers(true); } else { // Before (next instruction) it will saves current default // packages to the level, saving theses packages with the level this.addDefaultPackages(); // Make sure no data is lost if server decides to die // during a game and player forgot to /level save if (!getLevelLoader().saveLevel(getLevel())) { LogWarning(language.get("Warning.UnableToSaveLevel")); } else { LogInfo(language.get("Info.LevelSaved")); } if (this.getLevel().getSpawns().isEmpty()) { LogWarning(language.get("Warning.NoSpawns")); return false; } if (!config.PluginModeAutoStart) setWaitingForPlayers(false); isRunning = true; if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive) for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } else for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone && !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } getLevel().initSigns(); this.sortedStats.clear(); for (Player save : players.keySet()) //makes sure all inventorys have been saved { inventorySave.addInventory(save); save.getInventory().clear(); save.getInventory().setArmorContents(null); } for (PlayerStats stat : players.values()) { stat.resetPoints(); stat.resetMoney(); this.sortedStats.add(stat); } getWaveStarter().resetWave(); revivePlayers(true); getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay); } } return true; } public void stopRunning() { if (isRunning) { isRunning = false; getSpawnTimer().Stop(); getWaveStarter().cancelWave(); getSpawner().clearZombies(); getLevelSelector().cancelVote(); blockTrace.reverse(); deadPeople.clear(); TollSign.getAllowedPlayer().clear(); for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)"); } } for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends { fd.teleport(level.getInitialSpawn()); } if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) { players.clear(); } } } //to avoid warnings public boolean isWaitingForPlayers() { return waitingForPlayers; } //to avoid warnings public void setWaitingForPlayers(boolean waitingForPlayers) { this.waitingForPlayers = waitingForPlayers; } public boolean isCorrectWorld(World World) { if(config.PluginModeServerExclusive) { return true; //continue (ignore world) } else if(config.PluginModeWorldExclusive) { String world = World.toString(); String[] ar = world.split("="); if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName)) { return false; //your in wrong world } return true; //your in correct world } else { LogSevere("We have a big problem in isCorrectWorld()"); return true; //continue (ignore world) } } /* * public static void messagePlayer(CommandSender sender, String message) { if(message.isEmpty()) return; if (sender == null) Logger.getLogger("Minecraft").info(ChatColor.stripColor(message)); else sender.sendMessage(message); } */ public void messageTribuPlayers(String msg) //This wil message only the players (confused what this is for haha) { if(msg.isEmpty()) return; for(Player p : players.keySet()) { p.sendMessage(ChatColor.GRAY + "[Tribu] " + msg); } } public void messagePlayers(String message) //this will message ALL of the players in that world. { for(Player players:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) { players.sendMessage(ChatColor.GRAY + "[Tribu] " + message); } } public static void messagePlayer(CommandSender user, String message) //this will message a set player. { ((Player) user).sendMessage(ChatColor.GRAY + "[Tribu] " + message); } public Map<Player,String> deadPeople = new HashMap<Player,String>(); }
true
true
public void checkAliveCount() { // log.info("checking alive count " + aliveCount); int alive = players.size() - deadPeople.size(); if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used. deadPeople.clear(); stopRunning(); messagePlayers(language.get("Message.ZombieHavePrevailed")); messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber()))); if (getPlayersCount() != 0) getLevelSelector().startVote(Constants.VoteDelay); } } public int getAliveCount() { return aliveCount; } public BlockTrace getBlockTrace() { return blockTrace; } public TribuLevel getLevel() { return level; } public LevelFileLoader getLevelLoader() { return levelLoader; } public LevelSelector getLevelSelector() { return levelSelector; } public String getLocale(String key) { /* * String r = language.get(key); if (r == null) { LogWarning(key + * " not found"); r = ChatColor.RED + * "An error occured while getting this message"; } return r; */ return language.get(key); } public Set<Player> getPlayers() { return this.players.keySet(); } public int getPlayersCount() { return this.players.size(); } public Player getRandomPlayer() { return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer(); } public LinkedList<PlayerStats> getSortedStats() { Collections.sort(this.sortedStats); /* * Iterator<PlayerStats> i=this.sortedStats.iterator(); while * (i.hasNext()) { PlayerStats ps = i.next(); * LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); } */ return this.sortedStats; } public TribuSpawner getSpawner() { return spawner; } public SpawnTimer getSpawnTimer() { return spawnTimer; } public boolean isInsideLevel(Location loc) { if (isRunning && level != null) return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone); else return false; } public PlayerStats getStats(Player player) { return players.get(player); } public WaveStarter getWaveStarter() { return waveStarter; } private void initPluginMode() { if (config.PluginModeServerExclusive) { for (Player p : this.getServer().getOnlinePlayers()) this.addPlayer(p); } if(config.PluginModeWorldExclusive) { for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) { this.addPlayer(d); } } if (config.PluginModeDefaultLevel != "") setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel)); if (config.PluginModeAutoStart) startRunning(); } public void reloadConf() { this.reloadConfig(); this.loadCustomConf(); this.initPluginMode(); } public void loadCustomConf() { TribuLevel level=this.getLevel(); if (level == null) return; File worldFile = null, levelFile = null, worldDir, levelDir; worldDir = new File(Constants.perWorldFolder); levelDir = new File(Constants.perLevelFolder); String levelName = level.getName() + ".yml"; String worldName = level.getInitialSpawn().getWorld().getName() + ".yml"; if (!levelDir.exists()) levelDir.mkdirs(); if (!worldDir.exists()) worldDir.mkdirs(); for (File file : levelDir.listFiles()) { if (file.getName().equalsIgnoreCase(levelName)) { levelFile = file; break; } } for (File file : worldDir.listFiles()) { if (file.getName().equalsIgnoreCase(worldName)) { worldFile = file; break; } } if(levelFile!=null) if(worldFile != null) this.config=new TribuConfig(levelFile,new TribuConfig(worldFile)); else this.config=new TribuConfig(levelFile); else this.config=new TribuConfig(); /* try { config.set("DefaultPackages", null); config.load(Constants.configFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } if (worldFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } if (levelFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } */ } private void initLanguage() { DefaultLanguage.setAuthor("Graindcafe"); DefaultLanguage.setName("English"); DefaultLanguage.setVersion(Constants.LanguageFileVersion); DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar); DefaultLanguage.setLocales(new HashMap<String, String>() { private static final long serialVersionUID = 9166935722459443352L; { put("File.DefaultLanguageFile", "# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n"); put("File.LanguageFileComplete", "# Your language file is complete\n"); put("File.TranslationsToDo", "# Translations to do in this language file\n"); put("Sign.Buy", "Buy"); put("Sign.ToggleSpawner", "Spawn's switch"); put("Sign.Spawner", "Zombie Spawner"); put("Sign.HighscoreNames", "Top Names"); put("Sign.HighscorePoints", "Top Points"); put("Sign.TollSign", "Pay"); put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : "); put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item"); put("Message.ZombieSpawnList", ChatColor.GREEN + "%s"); put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command"); put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!"); put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded"); put("Message.InvalidVote", ChatColor.RED + "Invalid vote"); put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote"); put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time"); put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully"); put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level"); put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later"); put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later"); put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level"); put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,"); put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,"); put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn"); put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set."); put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn"); put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set."); put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level."); put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful"); put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created"); put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level."); put("Message.PackageCreated", ChatColor.RED + "Package created successfully"); put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully."); put("Message.Levels", ChatColor.GREEN + "Levels: %s"); put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s"); put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in."); put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!"); put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!"); put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added"); put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed"); put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name"); put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s"); put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item..."); put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $"); put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!"); put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s"); put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round"); put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!"); put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s"); put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies."); put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies."); put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added."); put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed."); put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it."); put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it."); put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded."); put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level."); put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package."); put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first."); put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id."); put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid."); put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created."); put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened."); put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed."); put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed."); put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted."); put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added."); put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added."); put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s."); put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified"); put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns."); put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry."); put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in."); put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen"); put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,"); put("Broadcast.Type", ChatColor.DARK_AQUA + "Type "); put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s"); put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds"); put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health"); put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds."); put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete"); put("Info.LevelFound", ChatColor.YELLOW + "%s levels found"); put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20"); put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu"); put("Info.LevelSaved", ChatColor.GREEN + "Level saved"); put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s."); put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist"); put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded."); put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level"); put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console"); put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete"); put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated"); put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing"); put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags."); put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'."); put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn."); put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !"); put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version"); put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist"); put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s"); put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s"); put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s"); put("Severe.Exception", ChatColor.RED + "Exception: %s"); put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)"); put("Message.PlayerDied",ChatColor.RED + "You are dead."); } }); language = Language.init(log, config.PluginModeLanguage); Constants.MessageMoneyPoints = language.get("Message.MoneyPoints"); Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList"); } public boolean isAlive(Player player) { return players.get(player).isalive(); } public TribuConfig config() { return config; } public boolean isPlaying(Player p) { return players.containsKey(p); } public boolean isRunning() { return isRunning; } public void keepTempInv(Player p, ItemStack[] items) { // log.info("Keep " + items.length + " items for " + // p.getDisplayName()); tempInventories.put(p, new TribuTempInventory(p, items)); } public void LogInfo(String message) { log.info("[Tribu] " + message); } public void LogSevere(String message) { log.severe("[Tribu] " + message); } public void LogWarning(String message) { log.warning("[Tribu] " + message); } @Override public void onDisable() { for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe(player + language.get("Severe.PlayerDidntGetInvBack")); } } players.clear(); sortedStats.clear(); stopRunning(); LogInfo(language.get("Info.Disable")); } @Override public void onEnable() { log = Logger.getLogger("Minecraft"); rnd = new Random(); Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar); this.config=new TribuConfig(); initLanguage(); try { @SuppressWarnings("rawtypes") Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE }; Method a = EntityTypes.class.getDeclaredMethod("a", args); a.setAccessible(true); a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893); a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893); } catch (Exception e) { e.printStackTrace(); setEnabled(false); return; } isRunning = false; aliveCount = 0; level = null; blockTrace = new BlockTrace(); tempInventories = new HashMap<Player, TribuTempInventory>(); inventorySave = new TribuInventory(); players = new HashMap<Player, PlayerStats>(); spawnPoint=new HashMap<Player,Location>(); sortedStats = new LinkedList<PlayerStats>(); levelLoader = new LevelFileLoader(this); levelSelector = new LevelSelector(this); spawner = new TribuSpawner(this); spawnTimer = new SpawnTimer(this); waveStarter = new WaveStarter(this); // Create listeners playerListener = new TribuPlayerListener(this); entityListener = new TribuEntityListener(this); blockListener = new TribuBlockListener(this); worldListener = new TribuWorldListener(this); this.initPluginMode(); this.loadCustomConf(); getServer().getPluginManager().registerEvents(playerListener, this); getServer().getPluginManager().registerEvents(entityListener, this); getServer().getPluginManager().registerEvents(blockListener, this); getServer().getPluginManager().registerEvents(worldListener, this); getCommand("dspawn").setExecutor(new CmdDspawn(this)); getCommand("zspawn").setExecutor(new CmdZspawn(this)); getCommand("ispawn").setExecutor(new CmdIspawn(this)); getCommand("tribu").setExecutor(new CmdTribu(this)); LogInfo(language.get("Info.Enable")); } public void resetedSpawnAdd(Player p,Location point) { spawnPoint.put(p, point); } public void removePlayer(Player player) { if (player != null && players.containsKey(player)) { if (isAlive(player)) { aliveCount--; } sortedStats.remove(players.get(player)); inventorySave.restoreInventory(player); players.remove(player); if(player.isOnline() && spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } // check alive AFTER player remove checkAliveCount(); if (!player.isDead()) restoreInventory(player); } } public void restoreInventory(Player p) { // log.info("Restore items for " + p.getDisplayName()); inventorySave.restoreInventory(p); } public void restoreTempInv(Player p) { // log.info("Restore items for " + p.getDisplayName()); if (tempInventories.containsKey(p)) tempInventories.remove(p).restore(); } public void revivePlayer(Player player) { if(spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } players.get(player).revive(); if (config.WaveStartHealPlayers) player.setHealth(20); restoreTempInv(player); aliveCount++; } public void revivePlayers(boolean teleportAll) { aliveCount = 0; for (Player player : players.keySet()) { revivePlayer(player); if (isRunning && level != null && (teleportAll || !isAlive(player))) { player.teleport(level.getInitialSpawn()); } } } public void setDead(Player player) { if (players.containsKey(player)) { if (isAlive(player)) { aliveCount--; PlayerStats p = players.get(player); p.resetMoney(); p.subtractmoney(config.StatsOnPlayerDeathMoney); p.subtractPoints(config.StatsOnPlayerDeathPoints); p.msgStats(); messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died."); /* * Set<Entry<Player, PlayerStats>> stats = players.entrySet(); * for (Entry<Player, PlayerStats> stat : stats) { * stat.getValue().subtractPoints(50); * stat.getValue().resetMoney(); stat.getValue().msgStats(); } */ } deadPeople.put(player,null); players.get(player).kill(); if (getLevel() != null && isRunning) { checkAliveCount(); } } } public void setLevel(TribuLevel level) { this.level = level; this.loadCustomConf(); } public boolean startRunning() { if (!isRunning && getLevel() != null) { if (players.isEmpty()) { setWaitingForPlayers(true); } else { // Before (next instruction) it will saves current default // packages to the level, saving theses packages with the level this.addDefaultPackages(); // Make sure no data is lost if server decides to die // during a game and player forgot to /level save if (!getLevelLoader().saveLevel(getLevel())) { LogWarning(language.get("Warning.UnableToSaveLevel")); } else { LogInfo(language.get("Info.LevelSaved")); } if (this.getLevel().getSpawns().isEmpty()) { LogWarning(language.get("Warning.NoSpawns")); return false; } if (!config.PluginModeAutoStart) setWaitingForPlayers(false); isRunning = true; if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive) for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } else for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone && !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } getLevel().initSigns(); this.sortedStats.clear(); for (Player save : players.keySet()) //makes sure all inventorys have been saved { inventorySave.addInventory(save); save.getInventory().clear(); save.getInventory().setArmorContents(null); } for (PlayerStats stat : players.values()) { stat.resetPoints(); stat.resetMoney(); this.sortedStats.add(stat); } getWaveStarter().resetWave(); revivePlayers(true); getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay); } } return true; } public void stopRunning() { if (isRunning) { isRunning = false; getSpawnTimer().Stop(); getWaveStarter().cancelWave(); getSpawner().clearZombies(); getLevelSelector().cancelVote(); blockTrace.reverse(); deadPeople.clear(); TollSign.getAllowedPlayer().clear(); for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)"); } } for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends { fd.teleport(level.getInitialSpawn()); } if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) { players.clear(); } } } //to avoid warnings public boolean isWaitingForPlayers() { return waitingForPlayers; } //to avoid warnings public void setWaitingForPlayers(boolean waitingForPlayers) { this.waitingForPlayers = waitingForPlayers; } public boolean isCorrectWorld(World World) { if(config.PluginModeServerExclusive) { return true; //continue (ignore world) } else if(config.PluginModeWorldExclusive) { String world = World.toString(); String[] ar = world.split("="); if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName)) { return false; //your in wrong world } return true; //your in correct world } else { LogSevere("We have a big problem in isCorrectWorld()"); return true; //continue (ignore world) } } /* * public static void messagePlayer(CommandSender sender, String message) { if(message.isEmpty()) return; if (sender == null) Logger.getLogger("Minecraft").info(ChatColor.stripColor(message)); else sender.sendMessage(message); }
public void checkAliveCount() { // log.info("checking alive count " + aliveCount); int alive = players.size() - deadPeople.size(); if (alive == 0 && isRunning) { //if (aliveCount == 0 && isRunning) { //if deadPeople isnt used. deadPeople.clear(); stopRunning(); messagePlayers(language.get("Message.ZombieHavePrevailed")); messagePlayers(String.format(language.get("Message.YouHaveReachedWave"), String.valueOf(getWaveStarter().getWaveNumber()))); if (getPlayersCount() != 0) getLevelSelector().startVote(Constants.VoteDelay); } } public int getAliveCount() { return aliveCount; } public BlockTrace getBlockTrace() { return blockTrace; } public TribuLevel getLevel() { return level; } public LevelFileLoader getLevelLoader() { return levelLoader; } public LevelSelector getLevelSelector() { return levelSelector; } public String getLocale(String key) { /* * String r = language.get(key); if (r == null) { LogWarning(key + * " not found"); r = ChatColor.RED + * "An error occured while getting this message"; } return r; */ return language.get(key); } public Set<Player> getPlayers() { return this.players.keySet(); } public int getPlayersCount() { return this.players.size(); } public Player getRandomPlayer() { return sortedStats.get(rnd.nextInt(sortedStats.size())).getPlayer(); } public LinkedList<PlayerStats> getSortedStats() { Collections.sort(this.sortedStats); /* * Iterator<PlayerStats> i=this.sortedStats.iterator(); while * (i.hasNext()) { PlayerStats ps = i.next(); * LogInfo(ps.getPlayer().getDisplayName() +" "+ ps.getPoints()); } */ return this.sortedStats; } public TribuSpawner getSpawner() { return spawner; } public SpawnTimer getSpawnTimer() { return spawnTimer; } public boolean isInsideLevel(Location loc) { if (isRunning && level != null) return config.PluginModeServerExclusive || config.PluginModeWorldExclusive || (loc.distance(level.getInitialSpawn()) < config.LevelClearZone); else return false; } public PlayerStats getStats(Player player) { return players.get(player); } public WaveStarter getWaveStarter() { return waveStarter; } private void initPluginMode() { if (config.PluginModeServerExclusive) { for (Player p : this.getServer().getOnlinePlayers()) this.addPlayer(p); } if(config.PluginModeWorldExclusive) { for(Player d:Bukkit.getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) { this.addPlayer(d); } } if (config.PluginModeDefaultLevel != "") setLevel(levelLoader.loadLevel(config.PluginModeDefaultLevel)); if (config.PluginModeAutoStart) startRunning(); } public void reloadConf() { this.reloadConfig(); this.loadCustomConf(); this.initPluginMode(); } public void loadCustomConf() { TribuLevel level=this.getLevel(); if (level == null) return; File worldFile = null, levelFile = null, worldDir, levelDir; worldDir = new File(Constants.perWorldFolder); levelDir = new File(Constants.perLevelFolder); String levelName = level.getName() + ".yml"; String worldName = level.getInitialSpawn().getWorld().getName() + ".yml"; if (!levelDir.exists()) levelDir.mkdirs(); if (!worldDir.exists()) worldDir.mkdirs(); for (File file : levelDir.listFiles()) { if (file.getName().equalsIgnoreCase(levelName)) { levelFile = file; break; } } for (File file : worldDir.listFiles()) { if (file.getName().equalsIgnoreCase(worldName)) { worldFile = file; break; } } if(levelFile!=null) if(worldFile != null) this.config=new TribuConfig(levelFile,new TribuConfig(worldFile)); else this.config=new TribuConfig(levelFile); else this.config=new TribuConfig(); /* try { config.set("DefaultPackages", null); config.load(Constants.configFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } if (worldFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(worldFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } if (levelFile != null) { YamlConfiguration tmpConf = YamlConfiguration.loadConfiguration(levelFile); for (String key : tmpConf.getKeys(true)) if (!config.isConfigurationSection(key)) config.set(key, tmpConf.get(key)); } */ } private void initLanguage() { DefaultLanguage.setAuthor("Graindcafe"); DefaultLanguage.setName("English"); DefaultLanguage.setVersion(Constants.LanguageFileVersion); DefaultLanguage.setLanguagesFolder(getDataFolder().getPath() + File.separatorChar + "languages" + File.separatorChar); DefaultLanguage.setLocales(new HashMap<String, String>() { private static final long serialVersionUID = 9166935722459443352L; { put("File.DefaultLanguageFile", "# This is your default language file \n# You should not edit it !\n# Create another language file (custom.yml) \n# and put 'Default: english' if your default language is english\n"); put("File.LanguageFileComplete", "# Your language file is complete\n"); put("File.TranslationsToDo", "# Translations to do in this language file\n"); put("Sign.Buy", "Buy"); put("Sign.ToggleSpawner", "Spawn's switch"); put("Sign.Spawner", "Zombie Spawner"); put("Sign.HighscoreNames", "Top Names"); put("Sign.HighscorePoints", "Top Points"); put("Sign.TollSign", "Pay"); put("Message.Stats", ChatColor.GREEN + "Ranking of best zombies killers : "); put("Message.UnknownItem", ChatColor.YELLOW + "Sorry, unknown item"); put("Message.ZombieSpawnList", ChatColor.GREEN + "%s"); put("Message.ConfirmDeletion", ChatColor.YELLOW + "Please confirm the deletion of the %s level by redoing the command"); put("Message.ThisOperationIsNotCancellable", ChatColor.RED + "This operation is not cancellable!"); put("Message.LevelUnloaded", ChatColor.GREEN + "Level successfully unloaded"); put("Message.InvalidVote", ChatColor.RED + "Invalid vote"); put("Message.ThankyouForYourVote", ChatColor.GREEN + "Thank you for your vote"); put("Message.YouCannotVoteAtThisTime", ChatColor.RED + "You cannot vote at this time"); put("Message.LevelLoadedSuccessfully", ChatColor.GREEN + "Level loaded successfully"); put("Message.LevelIsAlreadyTheCurrentLevel", ChatColor.RED + "Level %s is already the current level"); put("Message.UnableToSaveLevel", ChatColor.RED + "Unable to save level, try again later"); put("Message.UnableToCreatePackage", ChatColor.RED + "Unable to create package, try again later"); put("Message.UnableToLoadLevel", ChatColor.RED + "Unable to load level"); put("Message.NoLevelLoaded", ChatColor.YELLOW + "No level loaded, type '/tribu load' to load one,"); put("Message.NoLevelLoaded2", ChatColor.YELLOW + "or '/tribu create' to create a new one,"); put("Message.TeleportedToDeathSpawn", ChatColor.GREEN + "Teleported to death spawn"); put("Message.DeathSpawnSet", ChatColor.GREEN + "Death spawn set."); put("Message.TeleportedToInitialSpawn", ChatColor.GREEN + "Teleported to initial spawn"); put("Message.InitialSpawnSet", ChatColor.GREEN + "Initial spawn set."); put("Message.UnableToSaveCurrentLevel", ChatColor.RED + "Unable to save current level."); put("Message.LevelSaveSuccessful", ChatColor.GREEN + "Level save successful"); put("Message.LevelCreated", ChatColor.GREEN + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.GREEN + " created"); put("Message.UnableToDeleteLevel", ChatColor.RED + "Unable to delete current level."); put("Message.PackageCreated", ChatColor.RED + "Package created successfully"); put("Message.LevelDeleted", ChatColor.GREEN + "Level deleted successfully."); put("Message.Levels", ChatColor.GREEN + "Levels: %s"); put("Message.UnknownLevel", ChatColor.RED + "Unknown level: %s"); put("Message.MaybeNotSaved", ChatColor.YELLOW + "Maybe you have not saved this level or you have not set anything in."); put("Message.ZombieModeEnabled", ChatColor.GREEN + "Zombie Mode enabled!"); put("Message.ZombieModeDisabled", ChatColor.RED + "Zombie Mode disabled!"); put("Message.SpawnpointAdded", ChatColor.GREEN + "Spawnpoint added"); put("Message.SpawnpointRemoved", ChatColor.GREEN + "Spawnpoint removed"); put("Message.InvalidSpawnName", ChatColor.RED + "Invalid spawn name"); put("Message.TeleportedToZombieSpawn", ChatColor.GREEN + "Teleported to zombie spawn " + ChatColor.LIGHT_PURPLE + "%s"); put("Message.UnableToGiveYouThatItem", ChatColor.RED + "Unable to give you that item..."); put("Message.PurchaseSuccessfulMoney", ChatColor.GREEN + "Purchase successful." + ChatColor.DARK_GRAY + " Money: " + ChatColor.GRAY + "%s $"); put("Message.YouDontHaveEnoughMoney", ChatColor.DARK_RED + "You don't have enough money for that!"); put("Message.MoneyPoints", ChatColor.DARK_GRAY + "Money: " + ChatColor.GRAY + "%s $" + ChatColor.DARK_GRAY + " Points: " + ChatColor.GRAY + "%s"); put("Message.GameInProgress", ChatColor.YELLOW + "Game in progress, you will spawn next round"); put("Message.ZombieHavePrevailed", ChatColor.DARK_RED + "Zombies have prevailed!"); put("Message.YouHaveReachedWave", ChatColor.RED + "You have reached wave " + ChatColor.YELLOW + "%s"); put("Message.YouJoined", ChatColor.GOLD + "You joined the human strengths against zombies."); put("Message.YouLeft", ChatColor.GOLD + "You left the fight against zombies."); put("Message.TribuSignAdded", ChatColor.GREEN + "Tribu sign successfully added."); put("Message.TribuSignRemoved", ChatColor.GREEN + "Tribu sign successfully removed."); put("Message.ProtectedBlock", ChatColor.YELLOW + "Sorry, this sign is protected, please ask an operator to remove it."); put("Message.CannotPlaceASpecialSign", ChatColor.YELLOW + "Sorry, you cannot place a special signs, please ask an operator to do it."); put("Message.ConfigFileReloaded", ChatColor.GREEN + "Config files have been reloaded."); put("Message.PckNotFound", ChatColor.YELLOW + "Package %s not found in this level."); put("Message.PckNeedName", ChatColor.YELLOW + "You have to specify the name of the package."); put("Message.PckNeedOpen", ChatColor.YELLOW + "You have to open or create a package first."); put("Message.PckNeedId", ChatColor.YELLOW + "You have to specify the at least the id."); put("Message.PckNeedIdSubid", ChatColor.YELLOW + "You have to specify the id and subid."); put("Message.PckCreated", ChatColor.GREEN + "The package %s has been created."); put("Message.PckOpened", ChatColor.GREEN + "The package %s has been opened."); put("Message.PckSaved", ChatColor.GREEN + "The package %s has been saved and closed."); put("Message.PckRemoved", ChatColor.GREEN + "The package has been removed."); put("Message.PckItemDeleted", ChatColor.GREEN + "The item has been deleted."); put("Message.PckItemAdded", ChatColor.GREEN + "The item \"%s\" has been successfully added."); put("Message.PckItemAddFailed", ChatColor.YELLOW + "The item \"%s\" could not be added."); put("Message.PckList", ChatColor.GREEN + "Packages of this level : %s."); put("Message.PckNoneOpened", ChatColor.YELLOW + "none opened/specified"); put("Message.LevelNotReady", ChatColor.YELLOW + "The level is not ready to run. Make sure you create/load a level and that it contains zombie spawns."); put("Message.Deny", ChatColor.RED + "A zombie denied your action, sorry."); put("Message.AlreadyIn", ChatColor.YELLOW + "You are already in."); put("Broadcast.MapChosen", ChatColor.DARK_BLUE + "Level " + ChatColor.LIGHT_PURPLE + "%s" + ChatColor.DARK_BLUE + " has been chosen"); put("Broadcast.MapVoteStarting", ChatColor.DARK_AQUA + "Level vote starting,"); put("Broadcast.Type", ChatColor.DARK_AQUA + "Type "); put("Broadcast.SlashVoteForMap", ChatColor.GOLD + "'/tribu vote %s'" + ChatColor.DARK_AQUA + " for map " + ChatColor.BLUE + "%s"); put("Broadcast.VoteClosingInSeconds", ChatColor.DARK_AQUA + "Vote closing in %s seconds"); put("Broadcast.StartingWave", ChatColor.GRAY + "Starting wave " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + ", " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " Zombies @ " + ChatColor.DARK_RED + "%s" + ChatColor.GRAY + " health"); put("Broadcast.Wave", ChatColor.DARK_GRAY + "Wave " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " starting in " + ChatColor.DARK_RED + "%s" + ChatColor.DARK_GRAY + " seconds."); put("Broadcast.WaveComplete", ChatColor.GOLD + "Wave Complete"); put("Info.LevelFound", ChatColor.YELLOW + "%s levels found"); put("Info.Enable", ChatColor.WHITE + "Starting " + ChatColor.DARK_RED + "Tribu" + ChatColor.WHITE + " by Graindcafe, original author : samp20"); put("Info.Disable", ChatColor.YELLOW + "Stopping Tribu"); put("Info.LevelSaved", ChatColor.GREEN + "Level saved"); put("Info.ChosenLanguage", ChatColor.YELLOW + "Chosen language : %s (default). Provided by : %s."); put("Info.LevelFolderDoesntExist", ChatColor.RED + "Level folder doesn't exist"); put("Warning.AllSpawnsCurrentlyUnloaded", ChatColor.YELLOW + "All zombies spawns are currently unloaded."); put("Warning.UnableToSaveLevel", ChatColor.RED + "Unable to save level"); put("Warning.ThisCommandCannotBeUsedFromTheConsole", ChatColor.RED + "This command cannot be used from the console"); put("Warning.IOErrorOnFileDelete", ChatColor.RED + "IO error on file delete"); put("Warning.LanguageFileOutdated", ChatColor.RED + "Your current language file is outdated"); put("Warning.LanguageFileMissing", ChatColor.RED + "The chosen language file is missing"); put("Warning.UnableToAddSign", ChatColor.RED + "Unable to add sign, maybe you've changed your locales, or signs' tags."); put("Warning.UnknownFocus", ChatColor.RED + "The string given for the configuration Zombies.Focus is not recognized : %s . It could be 'None','Nearest','Random','DeathSpawn','InitialSpawn'."); put("Warning.NoSpawns", ChatColor.RED + "You didn't set any zombie spawn."); put("Severe.TribuCantMkdir", ChatColor.RED + "Tribu can't make dirs so it cannot create the level directory, you would not be able to save levels ! You can't use Tribu !"); put("Severe.WorldInvalidFileVersion", ChatColor.RED + "World invalid file version"); put("Severe.WorldDoesntExist", ChatColor.RED + "World doesn't exist"); put("Severe.ErrorDuringLevelLoading", ChatColor.RED + "Error during level loading : %s"); put("Severe.ErrorDuringLevelSaving", ChatColor.RED + "Error during level saving : %s"); put("Severe.PlayerHaveNotRetrivedHisItems", ChatColor.RED + "The player %s have not retrieved his items, they will be deleted ! Items list : %s"); put("Severe.Exception", ChatColor.RED + "Exception: %s"); put("Severe.PlayerDidntGetInvBack", ChatColor.RED + "didn't get his inventory back because he was returned null. (Maybe he was not in server?)"); put("Message.PlayerDied",ChatColor.RED + "You are dead."); put("Message.PlayerRevive",ChatColor.GREEN + "You have been revived."); } }); language = Language.init(log, config.PluginModeLanguage); Constants.MessageMoneyPoints = language.get("Message.MoneyPoints"); Constants.MessageZombieSpawnList = language.get("Message.ZombieSpawnList"); } public boolean isAlive(Player player) { return players.get(player).isalive(); } public TribuConfig config() { return config; } public boolean isPlaying(Player p) { return players.containsKey(p); } public boolean isRunning() { return isRunning; } public void keepTempInv(Player p, ItemStack[] items) { // log.info("Keep " + items.length + " items for " + // p.getDisplayName()); tempInventories.put(p, new TribuTempInventory(p, items)); } public void LogInfo(String message) { log.info("[Tribu] " + message); } public void LogSevere(String message) { log.severe("[Tribu] " + message); } public void LogWarning(String message) { log.warning("[Tribu] " + message); } @Override public void onDisable() { for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe(player + language.get("Severe.PlayerDidntGetInvBack")); } } players.clear(); sortedStats.clear(); stopRunning(); LogInfo(language.get("Info.Disable")); } @Override public void onEnable() { log = Logger.getLogger("Minecraft"); rnd = new Random(); Constants.rebuildPath(getDataFolder().getPath() + File.separatorChar); this.config=new TribuConfig(); initLanguage(); try { @SuppressWarnings("rawtypes") Class[] args = { Class.class, String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE }; Method a = EntityTypes.class.getDeclaredMethod("a", args); a.setAccessible(true); a.invoke(a, EntityTribuZombie.class, "Zombie", 54, '\uafaf', 7969893); a.invoke(a, EntityZombie.class, "Zombie", 54, '\uafaf', 7969893); } catch (Exception e) { e.printStackTrace(); setEnabled(false); return; } isRunning = false; aliveCount = 0; level = null; blockTrace = new BlockTrace(); tempInventories = new HashMap<Player, TribuTempInventory>(); inventorySave = new TribuInventory(); players = new HashMap<Player, PlayerStats>(); spawnPoint=new HashMap<Player,Location>(); sortedStats = new LinkedList<PlayerStats>(); levelLoader = new LevelFileLoader(this); levelSelector = new LevelSelector(this); spawner = new TribuSpawner(this); spawnTimer = new SpawnTimer(this); waveStarter = new WaveStarter(this); // Create listeners playerListener = new TribuPlayerListener(this); entityListener = new TribuEntityListener(this); blockListener = new TribuBlockListener(this); worldListener = new TribuWorldListener(this); this.initPluginMode(); this.loadCustomConf(); getServer().getPluginManager().registerEvents(playerListener, this); getServer().getPluginManager().registerEvents(entityListener, this); getServer().getPluginManager().registerEvents(blockListener, this); getServer().getPluginManager().registerEvents(worldListener, this); getCommand("dspawn").setExecutor(new CmdDspawn(this)); getCommand("zspawn").setExecutor(new CmdZspawn(this)); getCommand("ispawn").setExecutor(new CmdIspawn(this)); getCommand("tribu").setExecutor(new CmdTribu(this)); LogInfo(language.get("Info.Enable")); } public void resetedSpawnAdd(Player p,Location point) { spawnPoint.put(p, point); } public void removePlayer(Player player) { if (player != null && players.containsKey(player)) { if (isAlive(player)) { aliveCount--; } sortedStats.remove(players.get(player)); inventorySave.restoreInventory(player); players.remove(player); if(player.isOnline() && spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } // check alive AFTER player remove checkAliveCount(); if (!player.isDead()) restoreInventory(player); } } public void restoreInventory(Player p) { // log.info("Restore items for " + p.getDisplayName()); inventorySave.restoreInventory(p); } public void restoreTempInv(Player p) { // log.info("Restore items for " + p.getDisplayName()); if (tempInventories.containsKey(p)) tempInventories.remove(p).restore(); } public void revivePlayer(Player player) { if(spawnPoint.containsKey(player)) { player.setBedSpawnLocation(spawnPoint.remove(player)); } players.get(player).revive(); if (config.WaveStartHealPlayers) player.setHealth(20); restoreTempInv(player); aliveCount++; } public void revivePlayers(boolean teleportAll) { aliveCount = 0; for (Player player : players.keySet()) { revivePlayer(player); if (isRunning && level != null && (teleportAll || !isAlive(player))) { player.teleport(level.getInitialSpawn()); } } } public void setDead(Player player) { if (players.containsKey(player)) { if (isAlive(player)) { aliveCount--; PlayerStats p = players.get(player); p.resetMoney(); p.subtractmoney(config.StatsOnPlayerDeathMoney); p.subtractPoints(config.StatsOnPlayerDeathPoints); p.msgStats(); messagePlayers(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.RED + " has died."); /* * Set<Entry<Player, PlayerStats>> stats = players.entrySet(); * for (Entry<Player, PlayerStats> stat : stats) { * stat.getValue().subtractPoints(50); * stat.getValue().resetMoney(); stat.getValue().msgStats(); } */ } deadPeople.put(player,null); players.get(player).kill(); if (getLevel() != null && isRunning) { checkAliveCount(); } } } public void setLevel(TribuLevel level) { this.level = level; this.loadCustomConf(); } public boolean startRunning() { if (!isRunning && getLevel() != null) { if (players.isEmpty()) { setWaitingForPlayers(true); } else { // Before (next instruction) it will saves current default // packages to the level, saving theses packages with the level this.addDefaultPackages(); // Make sure no data is lost if server decides to die // during a game and player forgot to /level save if (!getLevelLoader().saveLevel(getLevel())) { LogWarning(language.get("Warning.UnableToSaveLevel")); } else { LogInfo(language.get("Info.LevelSaved")); } if (this.getLevel().getSpawns().isEmpty()) { LogWarning(language.get("Warning.NoSpawns")); return false; } if (!config.PluginModeAutoStart) setWaitingForPlayers(false); isRunning = true; if (config.PluginModeServerExclusive || config.PluginModeWorldExclusive) for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if (!(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } else for (LivingEntity e : level.getInitialSpawn().getWorld().getLivingEntities()) { if ((e.getLocation().distance(level.getInitialSpawn())) < config.LevelClearZone && !(e instanceof Player) && !(e instanceof Wolf) && !(e instanceof Villager)) e.damage(Integer.MAX_VALUE); } getLevel().initSigns(); this.sortedStats.clear(); for (Player save : players.keySet()) //makes sure all inventorys have been saved { inventorySave.addInventory(save); save.getInventory().clear(); save.getInventory().setArmorContents(null); } for (PlayerStats stat : players.values()) { stat.resetPoints(); stat.resetMoney(); this.sortedStats.add(stat); } getWaveStarter().resetWave(); revivePlayers(true); getWaveStarter().scheduleWave(Constants.TicksBySecond * config.WaveStartDelay); } } return true; } public void stopRunning() { if (isRunning) { isRunning = false; getSpawnTimer().Stop(); getWaveStarter().cancelWave(); getSpawner().clearZombies(); getLevelSelector().cancelVote(); blockTrace.reverse(); deadPeople.clear(); TollSign.getAllowedPlayer().clear(); for(String player:TribuInventory.inventories.keySet()) //this will only get players if the players inventory has been set. (for world Exclusive or server) { Player theplayer = Bukkit.getPlayer(player); if(theplayer != null) { inventorySave.restoreInventory(theplayer); } else { log.severe("[Tribu] " + player + " didn't get his inventory back because player was returned null. (Maybe he was not in server?)"); } } for(Player fd:Bukkit.getServer().getWorld(config.PluginModeWorldExclusiveWorldName).getPlayers()) //teleports all players to spawn when game ends { fd.teleport(level.getInitialSpawn()); } if (!config.PluginModeServerExclusive || !config.PluginModeWorldExclusive) { players.clear(); } } } //to avoid warnings public boolean isWaitingForPlayers() { return waitingForPlayers; } //to avoid warnings public void setWaitingForPlayers(boolean waitingForPlayers) { this.waitingForPlayers = waitingForPlayers; } public boolean isCorrectWorld(World World) { if(config.PluginModeServerExclusive) { return true; //continue (ignore world) } else if(config.PluginModeWorldExclusive) { String world = World.toString(); String[] ar = world.split("="); if(!ar[1].replace("}", "").equalsIgnoreCase(config.PluginModeWorldExclusiveWorldName)) { return false; //your in wrong world } return true; //your in correct world } else { LogSevere("We have a big problem in isCorrectWorld()"); return true; //continue (ignore world) } } /* * public static void messagePlayer(CommandSender sender, String message) { if(message.isEmpty()) return; if (sender == null) Logger.getLogger("Minecraft").info(ChatColor.stripColor(message)); else sender.sendMessage(message); }
diff --git a/apigenerator/src/com/android/apigenerator/Main.java b/apigenerator/src/com/android/apigenerator/Main.java index 8304f9870..5c26e14c8 100644 --- a/apigenerator/src/com/android/apigenerator/Main.java +++ b/apigenerator/src/com/android/apigenerator/Main.java @@ -1,166 +1,166 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.apigenerator; import com.android.apigenerator.enumfix.AndroidJarReader; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; /** * Main class for command line command to convert the existing API XML/TXT files into diff-based * simple text files. * */ public class Main { /** * @param args */ public static void main(String[] args) { if (args.length < 2 || args.length > 3) { printUsage(); } if (args.length == 3) { if (args[0].equals("enum")) { AndroidJarReader reader = new AndroidJarReader(args[1]); Map<String, ApiClass> classes = reader.getEnumClasses(); createApiFile(new File(args[2]), classes); } else { printUsage(); } } else { Map<String, ApiClass> classes = parsePlatformApiFiles(new File(args[0])); createApiFile(new File(args[1]), classes); } } private static void printUsage() { System.err.println("Convert API files into a more manageable file\n"); System.err.println("Usage\n"); System.err.println("\tApiCheck [enum] FOLDER OUTFILE\n"); System.exit(1); } /** * Parses platform API files. * @param apiFolder the folder containing the files. * @return a top level {@link ApiInfo} object for the highest available API level. */ private static Map<String, ApiClass> parsePlatformApiFiles(File apiFolder) { int apiLevel = 1; Map<String, ApiClass> map = new HashMap<String, ApiClass>(); InputStream stream = Main.class.getResourceAsStream( - "/com/android/apichecker/generator/enums.xml"); + "enums.xml"); if (stream != null) { map = EnumParser.parseApi(stream); } if (map == null) { map = new HashMap<String, ApiClass>(); } while (true) { File file = new File(apiFolder, Integer.toString(apiLevel) + ".xml"); if (file.exists()) { parseXmlApiFile(file, apiLevel, map); apiLevel++; } else { file = new File(apiFolder, Integer.toString(apiLevel) + ".txt"); if (file.exists()) { parseTxtApiFile(file, apiLevel, map); apiLevel++; } else { break; } } } return map; } private static void parseTxtApiFile(File apiFile, int api, Map<String, ApiClass> map) { try { NewApiParser.parseApi(apiFile.getName(), new FileInputStream(apiFile), map, api); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ApiParseException e) { e.printStackTrace(); } } private static void parseXmlApiFile(File apiFile, int apiLevel, Map<String, ApiClass> map) { try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); parser.parse(new FileInputStream(apiFile), new XmlApiParser(map, apiLevel)); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Creates the simplified diff-based API level. * @param outFolder the out folder. * @param classes */ private static void createApiFile(File outFile, Map<String, ApiClass> classes) { PrintStream ps = null; try { ps = new PrintStream(outFile); ps.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); ps.println("<api version=\"1\">"); TreeMap<String, ApiClass> map = new TreeMap<String, ApiClass>(classes); for (ApiClass theClass : map.values()) { (theClass).print(ps); } ps.println("</api>"); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }
true
true
private static Map<String, ApiClass> parsePlatformApiFiles(File apiFolder) { int apiLevel = 1; Map<String, ApiClass> map = new HashMap<String, ApiClass>(); InputStream stream = Main.class.getResourceAsStream( "/com/android/apichecker/generator/enums.xml"); if (stream != null) { map = EnumParser.parseApi(stream); } if (map == null) { map = new HashMap<String, ApiClass>(); } while (true) { File file = new File(apiFolder, Integer.toString(apiLevel) + ".xml"); if (file.exists()) { parseXmlApiFile(file, apiLevel, map); apiLevel++; } else { file = new File(apiFolder, Integer.toString(apiLevel) + ".txt"); if (file.exists()) { parseTxtApiFile(file, apiLevel, map); apiLevel++; } else { break; } } } return map; }
private static Map<String, ApiClass> parsePlatformApiFiles(File apiFolder) { int apiLevel = 1; Map<String, ApiClass> map = new HashMap<String, ApiClass>(); InputStream stream = Main.class.getResourceAsStream( "enums.xml"); if (stream != null) { map = EnumParser.parseApi(stream); } if (map == null) { map = new HashMap<String, ApiClass>(); } while (true) { File file = new File(apiFolder, Integer.toString(apiLevel) + ".xml"); if (file.exists()) { parseXmlApiFile(file, apiLevel, map); apiLevel++; } else { file = new File(apiFolder, Integer.toString(apiLevel) + ".txt"); if (file.exists()) { parseTxtApiFile(file, apiLevel, map); apiLevel++; } else { break; } } } return map; }
diff --git a/stock/src/com/zhangwei/stock/service/DailyStockScanService.java b/stock/src/com/zhangwei/stock/service/DailyStockScanService.java index 8e1c7aa..3d145f3 100644 --- a/stock/src/com/zhangwei/stock/service/DailyStockScanService.java +++ b/stock/src/com/zhangwei/stock/service/DailyStockScanService.java @@ -1,404 +1,404 @@ package com.zhangwei.stock.service; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.zhangwei.stock.MainActivity; import com.zhangwei.stock.R; import com.zhangwei.stock.gson.DailyList; import com.zhangwei.stock.gson.GoodStock; import com.zhangwei.stock.gson.Stock; import com.zhangwei.stock.gson.StockList; import com.zhangwei.stock.net.TencentStockHelper; import com.zhangwei.stock.net.WifiHelper; import com.zhangwei.stock.receiver.DailyReceiver; import com.zhangwei.stock.receiver.NetworkConnectChangedReceiver; import com.zhangwei.stock.utils.DateUtils; import com.zhangwei.stocklist.StockListHelper; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import cn.zipper.framwork.io.network.ZHttp2; import cn.zipper.framwork.io.network.ZHttpResponse; import cn.zipper.framwork.service.ZService; public class DailyStockScanService extends ZService { private final String TAG = "DailyStockScanService"; private AlarmManager alarms; private PendingIntent alarmIntent; //DailyList dailylist; StockList stocklist; private final long alarm_interval = 24*60*60*1000; //24 hour private DailyStockScanTask lastLookup; private KudnsRefreshTask lastRefresh; private final int HANDLER_FLAG_TODAY_COMPLETE = 0x12345612; private final int HANDLER_FLAG_TASK_COMPLETE = 0x12345678; private final int HANDLER_FLAG_WIFI_CONNECTED = 0x12345679; NetworkConnectChangedReceiver myBroadcastReceiver; @Override public void onCreate() { super.onCreate(); Log.e(TAG, "onCreate"); alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE); String ALARM_ACTION = DailyReceiver.ACTION_REFRESH_DAILYSCAN_ALARM; Intent intentToFire = new Intent(ALARM_ACTION); alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0); /* myBroadcastReceiver = new NetworkConnectChangedReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); this.registerReceiver(myBroadcastReceiver, filter);*/ /* LocalBroadcastManager.getInstance(this).registerReceiver(mWifiStatusReceiver, new IntentFilter(NetworkConnectChangedReceiver.ACTION_WIFI_CONNECTED));*/ } private BroadcastReceiver mWifiStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get extra data included in the Intent //String message = intent.getStringExtra("message"); Log.d("mWifiStatusReceiver", "Got message HANDLER_FLAG_WIFI_CONNECTED" ); //Message msg = handler.obtainMessage(HANDLER_FLAG_WIFI_CONNECTED); handler.sendEmptyMessageDelayed(HANDLER_FLAG_WIFI_CONNECTED, 10000); } }; @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "onDestroy"); /* this.unregisterReceiver(myBroadcastReceiver);*/ /* LocalBroadcastManager.getInstance(this).unregisterReceiver(mWifiStatusReceiver);*/ } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand, flags:" + flags + " startId" + startId); int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; long timeToRefresh = SystemClock.elapsedRealtime() + alarm_interval; alarms.setRepeating(alarmType, timeToRefresh, alarm_interval, alarmIntent); //alarms.cancel(alarmIntent); //dailylist = StockListHelper.getInstance().getDailyList(); stocklist = StockListHelper.getInstance().getStockList(); DailyStockScan(stocklist.getlastScanID()); //stocklist.seekTo("sh600055"); //DailyStockScan(stocklist.generateStockID(false)); return Service.START_STICKY; } private void showNotify(String title, String content){ int mId = 0x12345678; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle(title) .setContentText(content) .setAutoCancel(true); Intent resultIntent = new Intent(this, MainActivity.class); resultIntent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. Notification notification = mBuilder.getNotification(); notification.tickerText = title; notification.defaults = Notification.DEFAULT_SOUND | Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(mId, notification); } @Override public boolean handleMessage(Message msg) { // TODO Auto-generated method stub switch(msg.what){ case HANDLER_FLAG_TODAY_COMPLETE: break; case HANDLER_FLAG_TASK_COMPLETE: Log.e(TAG, "handle task complete, stopSelf"); String now = DateFormat.getDateInstance().format(new Date()); showNotify("扫描完成", now); this.stopSelf(); break; case HANDLER_FLAG_WIFI_CONNECTED: //只有在service活着的时候才能接收局部广播并重启service //应用在一次异步任务已退出,但没有完成(没有发出HANDLER_FLAG_TASK_COMPLETE) //这时的service还没有结束,等待网络状态的改变 Log.e(TAG, "handle wifi connected, refreshVersionCheck"); /* Intent startIntent = new Intent(this, DailyStockScanService.class); this.startService(startIntent);*/ //dailylist = StockListHelper.getInstance().getDailyList(); stocklist = StockListHelper.getInstance().getStockList(); DailyStockScan(stocklist.getlastScanID()); //refreshKudns_com(); break; } return false; } public void DailyStockScan(String stockID) { if (lastLookup==null || lastLookup.getStatus().equals(AsyncTask.Status.FINISHED)) { lastLookup = new DailyStockScanTask(handler); lastLookup.execute(stockID); } } public void refreshKudns_com() { if (lastRefresh==null || lastRefresh.getStatus().equals(AsyncTask.Status.FINISHED)) { lastRefresh = new KudnsRefreshTask(); lastRefresh.execute(); } } private class KudnsRefreshTask extends AsyncTask<Void,Void,Void>{ @Override protected Void doInBackground(Void... arg0) { // TODO Auto-generated method stub //GET /islogin.php HTTP/1.1 (必须,得到PHPSESSID) HashMap<String, String> headers = new HashMap<String, String>(); String cookie_str = "Hm_lvt_33ea14b096016df36e0a555e947b927e=1365233496,1365298626,1366705886;"; headers.put("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31"); headers.put("Cookie", cookie_str); ZHttp2 http2 = new ZHttp2(); http2.setHeaders(headers); ZHttpResponse httpResponse = http2.get("http://www.kudns.com/islogin.php"); Map<String, List<String>> ret = httpResponse.getHeaders(); List<String> list = ret.get("Set-Cookie"); Log.e(TAG, "set-cookie:" + list.get(0)); //POST /user/ilogin.php HTTP/1.1 (必须,登陆, 让phpsession合法) headers.put("Cookie", cookie_str + " " + list.get(0) + ";"); String post_data = "username=hustwei&pwd=lmx%401984&submit=%26%23160%3B%26%23160%3B%26%23160%3B%26%23160%3B"; httpResponse = http2.post("http://www.kudns.com/user/ilogin.php", post_data.getBytes()); ret = httpResponse.getHeaders(); //GET /user/host/add_date.php?Tid=81343 HTTP/1.1 headers.put("Cookie", cookie_str + " " + list.get(0) + ";"); http2.get("http://www.kudns.com/user/host/add_date.php?Tid=81343"); return null; } } /** * * @param 输入 上次记录的stock: sh600031(上次已完成) * @param 输出 这次完成的stock: sh600032 * * @author zhangwei * */ private class DailyStockScanTask extends AsyncTask<String,Void,String>{ private Handler handler; private boolean update; private boolean isAbort; private String completeID; public DailyStockScanTask(Handler handler) { // TODO Auto-generated constructor stub this.handler = handler; update = false; isAbort = false; completeID = null; } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub StockList stocklist = StockListHelper.getInstance().getStockList(); String curScanStockID = null; int errCount = 0; //连续出错计数 int retry = 0; //重试计数 //stocklist.setlastScanID("sz300355"); do{ Log.e(TAG, " lastStockID:" + curScanStockID + " errCount:" + errCount + " retry:" + retry); if(errCount<1){ curScanStockID = stocklist.getCurStockID(); Date lastscan_day = new Date(stocklist.getlastScanTime()); Date now_day = new Date(); if(curScanStockID.equals(StockList.TAIL)){ if(DateUtils.compareDay(lastscan_day, now_day)==0){ Log.e(TAG,"last scan time is the same day of the today, ingore"); - completeID = StockList.TAIL; + completeID = null;//StockList.TAIL; break; }else{ //new day stocklist.rewind(); errCount = 0; retry = 0; continue; } } }else{ if(TencentStockHelper.getInstance().judgeNetwork()){ Log.e(TAG, "www.baidu.com is ok"); //网络可用情况下,如果重试超过3次,则说明目的端有问题,取下一个 if(retry>3){ retry=0; errCount = 0; stocklist.next(); continue; } retry++; }else{ Log.e(TAG, "www.baidu.com not connected"); //没有网络就一直连接百度看是否能连上 try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Log.e(TAG, "curScanStockID:" + curScanStockID); //check net, only wifi can run if(!(WifiHelper.VALUE_WIFI.equals(WifiHelper.getNetType())||WifiHelper.VALUE_3G.equals(WifiHelper.getNetType()))){ Log.e(TAG, "WifiHelper, status:" + WifiHelper.getNetType() + " curScanStockID:" + curScanStockID); isAbort = true; break; } if(isCancelled()){ Log.e(TAG, "isCancelled, curScanStockID:" + curScanStockID); isAbort = true; break; } /*stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis());*/ Stock stock = TencentStockHelper.getInstance().get_stock_from_tencent(curScanStockID); if(stock!=null){ Log.e(TAG, "a stock done, stock.id:" + stock.id); //lastStockID = stock.id; //实时记录扫描的id到dailyList中 //stocklist.setlastScanID(lastStockID); update = true; completeID = stock.id; stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis()); errCount = 0; //对比laststock和这个stock是否有变化 Stock lastStock = StockListHelper.getInstance().getLastStock(stock.id); if(StockListHelper.isChangeStock(lastStock, stock)){ //save stock into history stocks StockListHelper.getInstance().persistHistoryStock(stock); //save stock into internal storage StockListHelper.getInstance().persistLastStock(stock); } StockListHelper.getInstance().persistStockList(stocklist); }else{ errCount++; } }while(curScanStockID!=null); Log.e(TAG, "loop over, update:" + update + " isAbort:" + isAbort + " completeID:" + completeID); if(update){ if(!isAbort){ //完成这次扫描(中途被终止的不算),记录时间 stocklist.setlastScanTime(System.currentTimeMillis()); } Log.e(TAG, "persistStockList!"); StockListHelper.getInstance().persistStockList(stocklist); } return completeID; } protected void onPostExecute(String result) { if(!isAbort && completeID!=null && completeID.equals(StockList.TAIL)){ handler.sendEmptyMessage(HANDLER_FLAG_TASK_COMPLETE); } } } }
true
true
protected String doInBackground(String... params) { // TODO Auto-generated method stub StockList stocklist = StockListHelper.getInstance().getStockList(); String curScanStockID = null; int errCount = 0; //连续出错计数 int retry = 0; //重试计数 //stocklist.setlastScanID("sz300355"); do{ Log.e(TAG, " lastStockID:" + curScanStockID + " errCount:" + errCount + " retry:" + retry); if(errCount<1){ curScanStockID = stocklist.getCurStockID(); Date lastscan_day = new Date(stocklist.getlastScanTime()); Date now_day = new Date(); if(curScanStockID.equals(StockList.TAIL)){ if(DateUtils.compareDay(lastscan_day, now_day)==0){ Log.e(TAG,"last scan time is the same day of the today, ingore"); completeID = StockList.TAIL; break; }else{ //new day stocklist.rewind(); errCount = 0; retry = 0; continue; } } }else{ if(TencentStockHelper.getInstance().judgeNetwork()){ Log.e(TAG, "www.baidu.com is ok"); //网络可用情况下,如果重试超过3次,则说明目的端有问题,取下一个 if(retry>3){ retry=0; errCount = 0; stocklist.next(); continue; } retry++; }else{ Log.e(TAG, "www.baidu.com not connected"); //没有网络就一直连接百度看是否能连上 try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Log.e(TAG, "curScanStockID:" + curScanStockID); //check net, only wifi can run if(!(WifiHelper.VALUE_WIFI.equals(WifiHelper.getNetType())||WifiHelper.VALUE_3G.equals(WifiHelper.getNetType()))){ Log.e(TAG, "WifiHelper, status:" + WifiHelper.getNetType() + " curScanStockID:" + curScanStockID); isAbort = true; break; } if(isCancelled()){ Log.e(TAG, "isCancelled, curScanStockID:" + curScanStockID); isAbort = true; break; } /*stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis());*/ Stock stock = TencentStockHelper.getInstance().get_stock_from_tencent(curScanStockID); if(stock!=null){ Log.e(TAG, "a stock done, stock.id:" + stock.id); //lastStockID = stock.id; //实时记录扫描的id到dailyList中 //stocklist.setlastScanID(lastStockID); update = true; completeID = stock.id; stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis()); errCount = 0; //对比laststock和这个stock是否有变化 Stock lastStock = StockListHelper.getInstance().getLastStock(stock.id); if(StockListHelper.isChangeStock(lastStock, stock)){ //save stock into history stocks StockListHelper.getInstance().persistHistoryStock(stock); //save stock into internal storage StockListHelper.getInstance().persistLastStock(stock); } StockListHelper.getInstance().persistStockList(stocklist); }else{ errCount++; } }while(curScanStockID!=null); Log.e(TAG, "loop over, update:" + update + " isAbort:" + isAbort + " completeID:" + completeID); if(update){ if(!isAbort){ //完成这次扫描(中途被终止的不算),记录时间 stocklist.setlastScanTime(System.currentTimeMillis()); } Log.e(TAG, "persistStockList!"); StockListHelper.getInstance().persistStockList(stocklist); } return completeID; }
protected String doInBackground(String... params) { // TODO Auto-generated method stub StockList stocklist = StockListHelper.getInstance().getStockList(); String curScanStockID = null; int errCount = 0; //连续出错计数 int retry = 0; //重试计数 //stocklist.setlastScanID("sz300355"); do{ Log.e(TAG, " lastStockID:" + curScanStockID + " errCount:" + errCount + " retry:" + retry); if(errCount<1){ curScanStockID = stocklist.getCurStockID(); Date lastscan_day = new Date(stocklist.getlastScanTime()); Date now_day = new Date(); if(curScanStockID.equals(StockList.TAIL)){ if(DateUtils.compareDay(lastscan_day, now_day)==0){ Log.e(TAG,"last scan time is the same day of the today, ingore"); completeID = null;//StockList.TAIL; break; }else{ //new day stocklist.rewind(); errCount = 0; retry = 0; continue; } } }else{ if(TencentStockHelper.getInstance().judgeNetwork()){ Log.e(TAG, "www.baidu.com is ok"); //网络可用情况下,如果重试超过3次,则说明目的端有问题,取下一个 if(retry>3){ retry=0; errCount = 0; stocklist.next(); continue; } retry++; }else{ Log.e(TAG, "www.baidu.com not connected"); //没有网络就一直连接百度看是否能连上 try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Log.e(TAG, "curScanStockID:" + curScanStockID); //check net, only wifi can run if(!(WifiHelper.VALUE_WIFI.equals(WifiHelper.getNetType())||WifiHelper.VALUE_3G.equals(WifiHelper.getNetType()))){ Log.e(TAG, "WifiHelper, status:" + WifiHelper.getNetType() + " curScanStockID:" + curScanStockID); isAbort = true; break; } if(isCancelled()){ Log.e(TAG, "isCancelled, curScanStockID:" + curScanStockID); isAbort = true; break; } /*stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis());*/ Stock stock = TencentStockHelper.getInstance().get_stock_from_tencent(curScanStockID); if(stock!=null){ Log.e(TAG, "a stock done, stock.id:" + stock.id); //lastStockID = stock.id; //实时记录扫描的id到dailyList中 //stocklist.setlastScanID(lastStockID); update = true; completeID = stock.id; stocklist.next(); stocklist.setlastScanTime(System.currentTimeMillis()); errCount = 0; //对比laststock和这个stock是否有变化 Stock lastStock = StockListHelper.getInstance().getLastStock(stock.id); if(StockListHelper.isChangeStock(lastStock, stock)){ //save stock into history stocks StockListHelper.getInstance().persistHistoryStock(stock); //save stock into internal storage StockListHelper.getInstance().persistLastStock(stock); } StockListHelper.getInstance().persistStockList(stocklist); }else{ errCount++; } }while(curScanStockID!=null); Log.e(TAG, "loop over, update:" + update + " isAbort:" + isAbort + " completeID:" + completeID); if(update){ if(!isAbort){ //完成这次扫描(中途被终止的不算),记录时间 stocklist.setlastScanTime(System.currentTimeMillis()); } Log.e(TAG, "persistStockList!"); StockListHelper.getInstance().persistStockList(stocklist); } return completeID; }
diff --git a/giraph/src/main/java/org/apache/giraph/counters/GiraphTimers.java b/giraph/src/main/java/org/apache/giraph/counters/GiraphTimers.java index 2a18987..a787b25 100644 --- a/giraph/src/main/java/org/apache/giraph/counters/GiraphTimers.java +++ b/giraph/src/main/java/org/apache/giraph/counters/GiraphTimers.java @@ -1,158 +1,158 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.giraph.counters; import org.apache.hadoop.mapreduce.Mapper.Context; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import java.util.Arrays; import java.util.Iterator; import java.util.Map; /** * Hadoop Counters in group "Giraph Timers" for timing things. */ public class GiraphTimers extends HadoopCountersBase { /** Counter group name for the giraph timers */ public static final String GROUP_NAME = "Giraph Timers"; /** Singleton instance for everyone to use */ private static GiraphTimers INSTANCE; /** Setup time in msec */ private static final int SETUP_MS = 0; /** Total time in msec */ private static final int TOTAL_MS = 1; /** Shutdown time in msec */ private static final int SHUTDOWN_MS = 2; /** How many whole job counters we have */ private static final int NUM_COUNTERS = 3; /** superstep time in msec */ private final Map<Long, GiraphHadoopCounter> superstepMsec; /** Whole job counters stored in this class */ private final GiraphHadoopCounter[] jobCounters; /** * Internal use only. Create using Hadoop Context * * @param context Hadoop Context to use. */ private GiraphTimers(Context context) { super(context, GROUP_NAME); jobCounters = new GiraphHadoopCounter[NUM_COUNTERS]; jobCounters[SETUP_MS] = getCounter("Setup (milliseconds)"); jobCounters[TOTAL_MS] = getCounter("Total (milliseconds)"); jobCounters[SHUTDOWN_MS] = getCounter("Shutdown (milliseconds)"); superstepMsec = Maps.newHashMap(); } /** * Instantiate with Hadoop Context. * * @param context Hadoop Context to use. */ public static void init(Context context) { INSTANCE = new GiraphTimers(context); } /** * Get singleton instance. * * @return singleton GiraphTimers instance. */ public static GiraphTimers getInstance() { return INSTANCE; } /** * Get counter for setup time in milliseconds * * @return Counter for setup time in milliseconds */ public GiraphHadoopCounter getSetupMs() { return jobCounters[SETUP_MS]; } /** * Get counter for superstep time in milliseconds * * @param superstep Integer superstep number. * @return Counter for setup time in milliseconds */ public GiraphHadoopCounter getSuperstepMs(long superstep) { GiraphHadoopCounter counter = superstepMsec.get(superstep); if (counter == null) { String counterPrefix; if (superstep == -1) { - counterPrefix = "Vertex input superstep"; + counterPrefix = "Input superstep"; } else { counterPrefix = "Superstep " + superstep; } counter = getCounter(counterPrefix + " (milliseconds)"); superstepMsec.put(superstep, counter); } return counter; } /** * Get counter for total time in milliseconds. * * @return Counter for total time in milliseconds. */ public GiraphHadoopCounter getTotalMs() { return jobCounters[TOTAL_MS]; } /** * Get counter for shutdown time in milliseconds. * * @return Counter for shutdown time in milliseconds. */ public GiraphHadoopCounter getShutdownMs() { return jobCounters[SHUTDOWN_MS]; } /** * Get map of superstep to msec counter. * * @return mapping of superstep to msec counter. */ public Map<Long, GiraphHadoopCounter> superstepCounters() { return superstepMsec; } /** * Get Iterable through job counters. * * @return Iterable of job counters. */ public Iterable<GiraphHadoopCounter> jobCounters() { return Arrays.asList(jobCounters); } @Override public Iterator<GiraphHadoopCounter> iterator() { return Iterators.concat(jobCounters().iterator(), superstepCounters().values().iterator()); } }
true
true
public GiraphHadoopCounter getSuperstepMs(long superstep) { GiraphHadoopCounter counter = superstepMsec.get(superstep); if (counter == null) { String counterPrefix; if (superstep == -1) { counterPrefix = "Vertex input superstep"; } else { counterPrefix = "Superstep " + superstep; } counter = getCounter(counterPrefix + " (milliseconds)"); superstepMsec.put(superstep, counter); } return counter; }
public GiraphHadoopCounter getSuperstepMs(long superstep) { GiraphHadoopCounter counter = superstepMsec.get(superstep); if (counter == null) { String counterPrefix; if (superstep == -1) { counterPrefix = "Input superstep"; } else { counterPrefix = "Superstep " + superstep; } counter = getCounter(counterPrefix + " (milliseconds)"); superstepMsec.put(superstep, counter); } return counter; }
diff --git a/service/src/main/java/com/shopzilla/ucla/cs130/seotool/team2/service/WebService.java b/service/src/main/java/com/shopzilla/ucla/cs130/seotool/team2/service/WebService.java index 374b196..6df7ed5 100644 --- a/service/src/main/java/com/shopzilla/ucla/cs130/seotool/team2/service/WebService.java +++ b/service/src/main/java/com/shopzilla/ucla/cs130/seotool/team2/service/WebService.java @@ -1,196 +1,196 @@ package com.shopzilla.ucla.cs130.seotool.team2.service; import com.shopzilla.ucla.cs130.seotool.team2.model.*; //import com.google.api.services.customsearch.*; import java.lang.String; import java.net.*; import java.io.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class WebService { private static final int numResults = 3; private static final String key = "AIzaSyB8JAz0MHfwz7s5e5Nv8jf-Ku_WlZbrpPM"; //private static final String bizSearchID = "013100502047583691894:1dyk11jghmi"; private static final String liveSearchID = "013036536707430787589:_pqjad5hr1a"; //private static final String shopzillaSearchID = "013100502047583691894:9ncazeorv5y"; // method for them to call public static WebPage[] service(String query, String targetsite){ //Jonathan's code here WebPage[] pages = new WebPage[numResults + 1]; for(int i = 0; i < numResults + 1; i++){ pages[i] = new WebPage(); } boolean done = false; try{ String line; StringBuilder build = new StringBuilder(); // form the url for the google query URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + liveSearchID + "&q=" + query+ "&alt=json"); // create the connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject JSONObject results = new JSONObject(build.toString()); // get the JSON element items JSONArray items = results.getJSONArray("items"); int size = items.length(); // array to store the links int j = 1; JSONObject temp; for(int i = 0; i < size; i++){ // grab each element in the array temp = items.getJSONObject(i); String tempurl = temp.getString("link"); // check if the link belongs to amazon or ebay if (tempurl.contains("amazon") || tempurl.contains("ebay")){ continue; } else if(tempurl.contains(targetsite)){ pages[0].set_url(tempurl); pages[0].set_rank(i+1); done = true; continue; } // grab the link and store into the array of links pages[j].set_url(tempurl); pages[j].set_rank(i+1); // links size counter j++; - if (j == numResults){ + if (j == numResults + 1){ break; } } // ------now get the target link link------------ if(!done){ /* // get a new StringBuilder so garbage isn't collected build = new StringBuilder(); if(targetsite.contains("bizrate")){ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + bizSearchID + "&q=" + query+ "&alt=json"); } else{ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + shopzillaSearchID + "&q=" + query+ "&alt=json"); } // create the connection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject results = new JSONObject(build.toString()); // get the JSON element items items = results.getJSONArray("items"); temp = items.getJSONObject(0); pages[0].set_url(temp.getString("link")); */ if(targetsite.contains("bizrate")){ String targeturl = "www.bizrate.com/classify?search_box=1&keyword=" + query; pages[0].set_url(targeturl); } else if(targetsite.contains("shopzilla")){ String targeturl = "www.shopzilla.com/search?seach_box=1&sfsk=0&cat_id=1&keyword=" + query; pages[0].set_url(targeturl); } } // works on local machine up to here } catch (IOException e){ System.err.println("Error during REST invocation of API!"); System.err.println("Exception Thrown: " + e.getMessage()); e.printStackTrace(); } catch (JSONException e){ System.err.println("Error during JSON construction!"); System.err.println("Exception Thrown: " +e.getMessage()); e.printStackTrace(); } //--------------------------------------------------------------------------------- //Albert's code here /* * add handling of cases where <100% of the pages are GET-able * add handling of more than top 3 pages * */ try { for(int i = 0; i < pages.length; i++) { //setup connection URL url = new URL(pages[i].get_url()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; String temp; //read the contents of the page while( (temp = rd.readLine()) != null) { content += temp; } //close buffered reader rd.close(); //fill our the WebPage object with content, keyword, and size pages[i].set_content(content); pages[i].set_keyword(query); pages[i].set_size(content.length()); //add ranking, however need to clarify which ranking it is. } } catch (Exception e) { //refine the possible error messages System.err.println("Error during webpage crawling"); e.printStackTrace(); } return pages; } }
true
true
public static WebPage[] service(String query, String targetsite){ //Jonathan's code here WebPage[] pages = new WebPage[numResults + 1]; for(int i = 0; i < numResults + 1; i++){ pages[i] = new WebPage(); } boolean done = false; try{ String line; StringBuilder build = new StringBuilder(); // form the url for the google query URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + liveSearchID + "&q=" + query+ "&alt=json"); // create the connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject JSONObject results = new JSONObject(build.toString()); // get the JSON element items JSONArray items = results.getJSONArray("items"); int size = items.length(); // array to store the links int j = 1; JSONObject temp; for(int i = 0; i < size; i++){ // grab each element in the array temp = items.getJSONObject(i); String tempurl = temp.getString("link"); // check if the link belongs to amazon or ebay if (tempurl.contains("amazon") || tempurl.contains("ebay")){ continue; } else if(tempurl.contains(targetsite)){ pages[0].set_url(tempurl); pages[0].set_rank(i+1); done = true; continue; } // grab the link and store into the array of links pages[j].set_url(tempurl); pages[j].set_rank(i+1); // links size counter j++; if (j == numResults){ break; } } // ------now get the target link link------------ if(!done){ /* // get a new StringBuilder so garbage isn't collected build = new StringBuilder(); if(targetsite.contains("bizrate")){ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + bizSearchID + "&q=" + query+ "&alt=json"); } else{ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + shopzillaSearchID + "&q=" + query+ "&alt=json"); } // create the connection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject results = new JSONObject(build.toString()); // get the JSON element items items = results.getJSONArray("items"); temp = items.getJSONObject(0); pages[0].set_url(temp.getString("link")); */ if(targetsite.contains("bizrate")){ String targeturl = "www.bizrate.com/classify?search_box=1&keyword=" + query; pages[0].set_url(targeturl); } else if(targetsite.contains("shopzilla")){ String targeturl = "www.shopzilla.com/search?seach_box=1&sfsk=0&cat_id=1&keyword=" + query; pages[0].set_url(targeturl); } } // works on local machine up to here } catch (IOException e){ System.err.println("Error during REST invocation of API!"); System.err.println("Exception Thrown: " + e.getMessage()); e.printStackTrace(); } catch (JSONException e){ System.err.println("Error during JSON construction!"); System.err.println("Exception Thrown: " +e.getMessage()); e.printStackTrace(); } //--------------------------------------------------------------------------------- //Albert's code here /* * add handling of cases where <100% of the pages are GET-able * add handling of more than top 3 pages * */ try { for(int i = 0; i < pages.length; i++) { //setup connection URL url = new URL(pages[i].get_url()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; String temp; //read the contents of the page while( (temp = rd.readLine()) != null) { content += temp; } //close buffered reader rd.close(); //fill our the WebPage object with content, keyword, and size pages[i].set_content(content); pages[i].set_keyword(query); pages[i].set_size(content.length()); //add ranking, however need to clarify which ranking it is. } } catch (Exception e) { //refine the possible error messages System.err.println("Error during webpage crawling"); e.printStackTrace(); } return pages; }
public static WebPage[] service(String query, String targetsite){ //Jonathan's code here WebPage[] pages = new WebPage[numResults + 1]; for(int i = 0; i < numResults + 1; i++){ pages[i] = new WebPage(); } boolean done = false; try{ String line; StringBuilder build = new StringBuilder(); // form the url for the google query URL url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + liveSearchID + "&q=" + query+ "&alt=json"); // create the connection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject JSONObject results = new JSONObject(build.toString()); // get the JSON element items JSONArray items = results.getJSONArray("items"); int size = items.length(); // array to store the links int j = 1; JSONObject temp; for(int i = 0; i < size; i++){ // grab each element in the array temp = items.getJSONObject(i); String tempurl = temp.getString("link"); // check if the link belongs to amazon or ebay if (tempurl.contains("amazon") || tempurl.contains("ebay")){ continue; } else if(tempurl.contains(targetsite)){ pages[0].set_url(tempurl); pages[0].set_rank(i+1); done = true; continue; } // grab the link and store into the array of links pages[j].set_url(tempurl); pages[j].set_rank(i+1); // links size counter j++; if (j == numResults + 1){ break; } } // ------now get the target link link------------ if(!done){ /* // get a new StringBuilder so garbage isn't collected build = new StringBuilder(); if(targetsite.contains("bizrate")){ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + bizSearchID + "&q=" + query+ "&alt=json"); } else{ url = new URL("https://www.googleapis.com/customsearch/v1?key=" + key +"&cx=" + shopzillaSearchID + "&q=" + query+ "&alt=json"); } // create the connection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // grab the reply br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); while((line = br.readLine()) != null){ build.append(line); } // close the reader br.close(); // create the JSONObject results = new JSONObject(build.toString()); // get the JSON element items items = results.getJSONArray("items"); temp = items.getJSONObject(0); pages[0].set_url(temp.getString("link")); */ if(targetsite.contains("bizrate")){ String targeturl = "www.bizrate.com/classify?search_box=1&keyword=" + query; pages[0].set_url(targeturl); } else if(targetsite.contains("shopzilla")){ String targeturl = "www.shopzilla.com/search?seach_box=1&sfsk=0&cat_id=1&keyword=" + query; pages[0].set_url(targeturl); } } // works on local machine up to here } catch (IOException e){ System.err.println("Error during REST invocation of API!"); System.err.println("Exception Thrown: " + e.getMessage()); e.printStackTrace(); } catch (JSONException e){ System.err.println("Error during JSON construction!"); System.err.println("Exception Thrown: " +e.getMessage()); e.printStackTrace(); } //--------------------------------------------------------------------------------- //Albert's code here /* * add handling of cases where <100% of the pages are GET-able * add handling of more than top 3 pages * */ try { for(int i = 0; i < pages.length; i++) { //setup connection URL url = new URL(pages[i].get_url()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; String temp; //read the contents of the page while( (temp = rd.readLine()) != null) { content += temp; } //close buffered reader rd.close(); //fill our the WebPage object with content, keyword, and size pages[i].set_content(content); pages[i].set_keyword(query); pages[i].set_size(content.length()); //add ranking, however need to clarify which ranking it is. } } catch (Exception e) { //refine the possible error messages System.err.println("Error during webpage crawling"); e.printStackTrace(); } return pages; }
diff --git a/src/share/impl/presentation/classes/com/sun/jumpimpl/module/presentation/PresentationModuleFactoryImpl.java b/src/share/impl/presentation/classes/com/sun/jumpimpl/module/presentation/PresentationModuleFactoryImpl.java index 4a189b1..d1716c2 100644 --- a/src/share/impl/presentation/classes/com/sun/jumpimpl/module/presentation/PresentationModuleFactoryImpl.java +++ b/src/share/impl/presentation/classes/com/sun/jumpimpl/module/presentation/PresentationModuleFactoryImpl.java @@ -1,75 +1,75 @@ /* * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. */ package com.sun.jumpimpl.module.presentation; import com.sun.jump.module.presentation.JUMPPresentationModule; import com.sun.jump.module.presentation.JUMPPresentationModuleFactory; import java.util.Map; public class PresentationModuleFactoryImpl extends JUMPPresentationModuleFactory { private JUMPPresentationModule simpleBasisAMS = null; private Map configMap; /** * load this module with the given properties * @param map properties of this module */ public void load(Map map) { this.configMap = map; } /** * unload the module */ public void unload() { } /** * Returns a <code>JUMPPresentationModule</code> for the specified * presentation mode. * @param presentation the application model for which an appropriate * installer module should be returned. * @return installer module object */ public JUMPPresentationModule getModule(String presentation) { if (presentation.equals(JUMPPresentationModuleFactory.SIMPLE_BASIS_AMS)) { return getSimpleBasisAMS(); } else { throw new IllegalArgumentException("Illegal JUMP Presentation Mode: " + presentation); } } private JUMPPresentationModule getSimpleBasisAMS() { synchronized(PresentationModuleFactoryImpl.class) { if (simpleBasisAMS == null) { - simpleBasisAMS = new com.sun.jumpimpl.presentation.simplebasis.SimpleBasisAMS(); + simpleBasisAMS = (JUMPPresentationModule)new com.sun.jumpimpl.presentation.simplebasis.SimpleBasisAMS(); simpleBasisAMS.load(configMap); } return simpleBasisAMS; } } }
true
true
private JUMPPresentationModule getSimpleBasisAMS() { synchronized(PresentationModuleFactoryImpl.class) { if (simpleBasisAMS == null) { simpleBasisAMS = new com.sun.jumpimpl.presentation.simplebasis.SimpleBasisAMS(); simpleBasisAMS.load(configMap); } return simpleBasisAMS; } }
private JUMPPresentationModule getSimpleBasisAMS() { synchronized(PresentationModuleFactoryImpl.class) { if (simpleBasisAMS == null) { simpleBasisAMS = (JUMPPresentationModule)new com.sun.jumpimpl.presentation.simplebasis.SimpleBasisAMS(); simpleBasisAMS.load(configMap); } return simpleBasisAMS; } }
diff --git a/src/main/java/water/fvec/Frame.java b/src/main/java/water/fvec/Frame.java index 2fa2be1a7..11ec1871c 100644 --- a/src/main/java/water/fvec/Frame.java +++ b/src/main/java/water/fvec/Frame.java @@ -1,753 +1,754 @@ package water.fvec; import java.io.IOException; import java.io.InputStream; import java.util.*; import water.*; import water.H2O.H2OCountedCompleter; import water.exec.Flow; import water.fvec.Vec.VectorGroup; import com.google.common.base.Throwables; /** * A collection of named Vecs. Essentially an R-like data-frame. Multiple * Frames can reference the same Vecs. A Frame is a lightweight object, it is * meant to be cheaply created and discarded for data munging purposes. * E.g. to exclude a Vec from a computation on a Frame, create a new Frame that * references all the Vecs but this one. */ public class Frame extends Iced { public String[] _names; Key[] _keys; // Keys for the vectors transient Vec[] _vecs;// The Vectors (transient to avoid network traffic) private transient Vec _col0; // First readable vec; fast access to the VectorGroup's Chunk layout public Frame( Frame fr ) { this(fr._names.clone(), fr.vecs().clone()); _col0 = fr._col0; } public Frame( Vec... vecs ){ this(null,vecs);} public Frame( String[] names, Vec[] vecs ) { // assert names==null || names.length == vecs.length : "Number of columns does not match to number of cols' names."; _names=names; _vecs=vecs; _keys = new Key[vecs.length]; for( int i=0; i<vecs.length; i++ ) { Key k = _keys[i] = vecs[i]._key; if( DKV.get(k)==null ) // If not already in KV, put it there DKV.put(k,vecs[i]); } Vec v0 = anyVec(); if( v0 == null ) return; VectorGroup grp = v0.group(); for( int i=0; i<vecs.length; i++ ) assert grp.equals(vecs[i].group()); } public Vec vec(String name){ Vec [] vecs = vecs(); for(int i = 0; i < _names.length; ++i) if(_names[i].equals(name))return vecs[i]; return null; } public Frame subframe(String [] names){ Vec [] vecs = new Vec[names.length]; HashMap<String, Integer> map = new HashMap<String, Integer>(); for(int i = 0; i < _names.length; ++i)map.put(_names[i], i); for(int i = 0; i < names.length; ++i) if(map.containsKey(names[i]))vecs[i] = _vecs[map.get(names[i])]; else throw new IllegalArgumentException("Missing column called "+names[i]); return new Frame(names,vecs); } public final Vec[] vecs() { if( _vecs != null ) return _vecs; // Load all Vec headers; load them all in parallel by spawning F/J tasks. final Vec [] vecs = new Vec[_keys.length]; Futures fs = new Futures(); for( int i=0; i<_keys.length; i++ ) { final int ii = i; final Key k = _keys[i]; H2OCountedCompleter t = new H2OCountedCompleter() { // We need higher priority here as there is a danger of deadlock in // case of many calls from MRTask2 at once (e.g. frame with many // vectors invokes rollup tasks for all vectors in parallel). Should // probably be done in CPS style in the future @Override public byte priority(){return H2O.MIN_HI_PRIORITY;} @Override public void compute2() { vecs[ii] = DKV.get(k).get(); tryComplete(); } }; H2O.submitTask(t); fs.add(t); } fs.blockForPending(); return _vecs = vecs; } // Force a cache-flush & reload, assuming vec mappings were altered remotely public final Vec[] reloadVecs() { _vecs=null; return vecs(); } /** Finds the first column with a matching name. */ public int find( String name ) { for( int i=0; i<_names.length; i++ ) if( name.equals(_names[i]) ) return i; return -1; } public int find( Vec vec ) { for( int i=0; i<_vecs.length; i++ ) if( vec.equals(_vecs[i]) ) return i; return -1; } /** Appends a named column, keeping the last Vec as the response */ public void add( String name, Vec vec ) { assert _vecs.length == 0 || anyVec().group().equals(vec.group()); final int len = _names.length; _names = Arrays.copyOf(_names,len+1); _vecs = Arrays.copyOf(_vecs ,len+1); _keys = Arrays.copyOf(_keys ,len+1); _names[len] = name; _vecs [len] = vec ; _keys [len] = vec._key; } /** Appends an entire Frame */ public Frame add( Frame fr ) { assert anyVec().group().equals(fr.anyVec().group()); final int len0= _names.length; final int len1= fr._names.length; final int len = len0+len1; _names = Arrays.copyOf(_names,len); _vecs = Arrays.copyOf(_vecs ,len); _keys = Arrays.copyOf(_keys ,len); System.arraycopy(fr._names,0,_names,len0,len1); System.arraycopy(fr._vecs ,0,_vecs ,len0,len1); System.arraycopy(fr._keys ,0,_keys ,len0,len1); return this; } /** Removes the first column with a matching name. */ public Vec remove( String name ) { return remove(find(name)); } /** Removes a numbered column. */ public Vec [] remove( int [] idxs ) { for(int i :idxs)if(i < 0 || i > _vecs.length) throw new ArrayIndexOutOfBoundsException(); Arrays.sort(idxs); Vec [] res = new Vec[idxs.length]; Vec [] rem = new Vec[_vecs.length-idxs.length]; String [] names = new String[rem.length]; Key [] keys = new Key [rem.length]; int j = 0; int k = 0; int l = 0; for(int i = 0; i < _vecs.length; ++i) if(j < idxs.length && i == idxs[j]){ ++j; res[k++] = _vecs[i]; } else { rem [l] = _vecs [i]; names[l] = _names[i]; keys [l] = _keys [i]; ++l; } _vecs = rem; _names = names; _keys = keys; assert l == rem.length && k == idxs.length; return res; } /** Removes a numbered column. */ public Vec remove( int idx ) { int len = _names.length; if( idx < 0 || idx >= len ) return null; Vec v = _vecs[idx]; System.arraycopy(_names,idx+1,_names,idx,len-idx-1); System.arraycopy(_vecs ,idx+1,_vecs ,idx,len-idx-1); System.arraycopy(_keys ,idx+1,_keys ,idx,len-idx-1); _names = Arrays.copyOf(_names,len-1); _vecs = Arrays.copyOf(_vecs ,len-1); _keys = Arrays.copyOf(_keys ,len-1); if( v == _col0 ) _col0 = null; return v; } /** * Remove given interval of columns from frame. Motivated by R intervals. * @param startIdx - start index of column (inclusive) * @param endIdx - end index of column (exclusive) * @return an array of remove columns */ public Vec[] remove(int startIdx, int endIdx) { int len = _names.length; int nlen = len - (endIdx-startIdx); String[] names = new String[nlen]; Key[] keys = new Key[nlen]; Vec[] vecs = new Vec[nlen]; if (startIdx > 0) { System.arraycopy(_names, 0, names, 0, startIdx); System.arraycopy(_vecs, 0, vecs, 0, startIdx); System.arraycopy(_keys, 0, keys, 0, startIdx); } nlen -= startIdx; if (endIdx < _names.length+1) { System.arraycopy(_names, endIdx, names, startIdx, nlen); System.arraycopy(_vecs, endIdx, vecs, startIdx, nlen); System.arraycopy(_keys, endIdx, keys, startIdx, nlen); } Vec[] vec = Arrays.copyOfRange(vecs(),startIdx,endIdx); _names = names; _vecs = vec; _keys = keys; _col0 = null; return vec; } public Vec replace(int col, Vec nv) { assert col < _names.length; Vec rv = vecs()[col]; assert rv.group().equals(nv.group()); _vecs[col] = nv; _keys[col] = nv._key; if( DKV.get(nv._key)==null ) // If not already in KV, put it there DKV.put(nv._key, nv); return rv; } public Frame extractFrame(int startIdx, int endIdx) { Frame f = subframe(startIdx, endIdx); remove(startIdx, endIdx); return f; } /** Create a subframe from given interval of columns. * * @param startIdx index of first column (inclusive) * @param endIdx index of the last column (exclusive) * @return a new frame containing specified interval of columns */ public Frame subframe(int startIdx, int endIdx) { Frame result = new Frame(Arrays.copyOfRange(_names,startIdx,endIdx),Arrays.copyOfRange(vecs(),startIdx,endIdx)); return result; } public final String[] names() { return _names; } public int numCols() { return vecs().length; } public long numRows(){ return anyVec().length();} // Number of columns when categoricals expanded. // Note: One level is dropped in each categorical col. public int numExpCols() { int ncols = 0; for(int i = 0; i < vecs().length; i++) ncols += vecs()[i].domain() == null ? 1 : (vecs()[i].domain().length - 1); return ncols; } /** All the domains for enum columns; null for non-enum columns. */ public String[][] domains() { String ds[][] = new String[vecs().length][]; for( int i=0; i<vecs().length; i++ ) ds[i] = vecs()[i].domain(); return ds; } private String[][] domains(int [] cols){ Vec [] vecs = vecs(); String [][] res = new String[cols.length][]; for(int i = 0; i < cols.length; ++i) res[i] = vecs[cols[i]]._domain; return res; } private String [] names(int [] cols){ if(_names == null)return null; String [] res = new String[cols.length]; for(int i = 0; i < cols.length; ++i) res[i] = _names[cols[i]]; return res; } public Vec lastVec() { final Vec [] vecs = vecs(); return vecs[vecs.length-1]; } /** Returns the first readable vector. */ public Vec anyVec() { if( _col0 != null ) return _col0; for( Vec v : vecs() ) if( v.readable() ) return (_col0 = v); return null; } /** Check that the vectors are all compatible. All Vecs have their content * sharded using same number of rows per chunk. */ public void checkCompatible( ) { try{ Vec v0 = anyVec(); int nchunks = v0.nChunks(); for( Vec vec : vecs() ) { if( vec instanceof AppendableVec ) continue; // New Vectors are endlessly compatible if( vec.nChunks() != nchunks ) throw new IllegalArgumentException("Vectors different numbers of chunks, "+nchunks+" and "+vec.nChunks()); } // Also check each chunk has same rows for( int i=0; i<nchunks; i++ ) { long es = v0.chunk2StartElem(i); for( Vec vec : vecs() ) if( !(vec instanceof AppendableVec) && vec.chunk2StartElem(i) != es ) throw new IllegalArgumentException("Vector chunks different numbers of rows, "+es+" and "+vec.chunk2StartElem(i)); } }catch(Throwable ex){ Throwables.propagate(ex); } } public void closeAppendables() {closeAppendables(new Futures()).blockForPending(); } // Close all AppendableVec public Futures closeAppendables(Futures fs) { _col0 = null; // Reset cache int len = vecs().length; for( int i=0; i<len; i++ ) { Vec v = _vecs[i]; if( v instanceof AppendableVec ) DKV.put(_keys[i],_vecs[i] = ((AppendableVec)v).close(fs),fs); } return fs; } public void remove() { remove(new Futures()); } /** Actually remove/delete all Vecs from memory, not just from the Frame. */ public void remove(Futures fs){ if(vecs().length > 0){ for( Vec v : _vecs ) UKV.remove(v._key,fs); } _names = new String[0]; _vecs = new Vec[0]; _keys = new Key[0]; } public long byteSize() { long sum=0; for( int i=0; i<vecs().length; i++ ) sum += _vecs[i].byteSize(); return sum; } @Override public String toString() { // Across Vec vecs[] = vecs(); if( vecs.length==0 ) return "{}"; String s="{"+_names[0]; long bs=vecs[0].byteSize(); for( int i=1; i<vecs.length; i++ ) { s += ","+_names[i]; bs+= vecs[i].byteSize(); } s += "}, "+PrettyPrint.bytes(bs)+"\n"; // Down Vec v0 = anyVec(); if( v0 == null ) return s; int nc = v0.nChunks(); s += "Chunk starts: {"; for( int i=0; i<nc; i++ ) s += v0.elem2BV(i)._start+","; s += "}"; return s; } // Print a row with headers inlined private String toStr( long idx, int col ) { return _names[col]+"="+(_vecs[col].isNA(idx) ? "NA" : _vecs[col].at(idx)); } public String toString( long idx ) { String s="{"+toStr(idx,0); for( int i=1; i<_names.length; i++ ) s += ","+toStr(idx,i); return s+"}"; } // Print fixed-width row & fixed-width headers (more compressed print // format). Returns the column formats. public String[] toStringHdr( StringBuilder sb ) { String[] fs = new String[numCols()]; for( int c=0; c<fs.length; c++ ) { String n = (c < _names.length) ? _names[c] : ("C"+c); if( numRows()==0 ) { sb.append(n).append(' '); continue; } int w=0; if( _vecs[c].isEnum() ) { String ss[] = _vecs[c]._domain; for( int i=0; i<ss.length; i++ ) w = Math.max(w,ss[i].length()); w = Math.min(w,10); fs[c] = "%"+w+"."+w+"s"; } else { Chunk C = _vecs[c].elem2BV(0); // 1st Chunk String f = fs[c] = C.pformat(); // Printable width for( int x=0; x<f.length(); x++ )// Get printable width from format if( Character.isDigit(f.charAt(x)) ) w = w*10+(f.charAt(x)-'0'); else if( w>0 ) break; if( f.charAt(1)==' ' ) w++; // Leading blank is not in print-width } int len = sb.length(); if( n.length() <= w ) { // Short name, big digits sb.append(n); for( int i=n.length(); i<w; i++ ) sb.append(' '); } else if( w==1 ) { // First char only sb.append(n.charAt(0)); } else if( w==2 ) { // First 2 chars only sb.append(n.charAt(0)).append(n.charAt(1)); } else { // First char dot lastchars; e.g. Compress "Interval" to "I.val" sb.append(n.charAt(0)).append('.'); for( int i=n.length()-(w-2); i<n.length(); i++ ) sb.append(n.charAt(i)); } assert len+w==sb.length(); sb.append(' '); // Column seperator } sb.append('\n'); return fs; } public StringBuilder toString( StringBuilder sb, String[] fs, long idx ) { Vec vecs[] = vecs(); for( int c=0; c<fs.length; c++ ) { Vec vec = vecs[c]; if( vec.isEnum() ) { String s = "----------"; if( !vec.isNA(idx) ) { int x = (int)vec.at8(idx); if( x >= 0 && x < vec._domain.length ) s = vec._domain[x]; } sb.append(String.format(fs[c],s)); } else if( vec.isInt() ) { if( vec.isNA(idx) ) { Chunk C = vec.elem2BV(0); // 1st Chunk int len = C.pformat_len0(); // Printable width for( int i=0; i<len; i++ ) sb.append('-'); } else { try { sb.append(String.format(fs[c],vec.at8(idx))); } catch( IllegalFormatException ife ) { System.out.println("Format: "+fs[c]+" col="+c+" not for ints"); ife.printStackTrace(); } } } else { sb.append(String.format(fs[c],vec.at (idx))); if( vec.isNA(idx) ) sb.append(' '); } sb.append(' '); // Column seperator } sb.append('\n'); return sb; } public String toStringAll() { StringBuilder sb = new StringBuilder(); String[] fs = toStringHdr(sb); for( int i=0; i<numRows(); i++ ) toString(sb,fs,i); return sb.toString(); } // Return the entire Frame as a CSV stream public InputStream toCSV(boolean headers) { return new CSVStream(headers); } private class CSVStream extends InputStream { byte[] _line; int _position; long _row; CSVStream(boolean headers) { StringBuilder sb = new StringBuilder(); if( headers ) { sb.append('"' + _names[0] + '"'); for(int i = 1; i < _vecs.length; i++) sb.append(',').append('"' + _names[i] + '"'); sb.append('\n'); } _line = sb.toString().getBytes(); } @Override public int available() throws IOException { if(_position == _line.length) { if(_row == numRows()) return 0; StringBuilder sb = new StringBuilder(); for( int i = 0; i < _vecs.length; i++ ) { if(i > 0) sb.append(','); if(!_vecs[i].isNA(_row)) { if(_vecs[i].isEnum()) sb.append('"' + _vecs[i]._domain[(int) _vecs[i].at8(_row)] + '"'); else if(_vecs[i].isInt()) sb.append(_vecs[i].at8(_row)); else sb.append(_vecs[i].at(_row)); } } sb.append('\n'); _line = sb.toString().getBytes(); _position = 0; _row++; } return _line.length - _position; } @Override public void close() throws IOException { super.close(); _line = null; } @Override public int read() throws IOException { return available() == 0 ? -1 : _line[_position++]; } @Override public int read(byte[] b, int off, int len) throws IOException { int n = available(); if(n > 0) { n = Math.min(n, len); System.arraycopy(_line, _position, b, off, n); _position += n; } return n; } } // -------------------------------------------------------------------------- // In support of R, a generic Deep Copy & Slice. // Semantics are a little odd, to match R's. // Each dimension spec can be: // null - all of them // a sorted list of negative numbers (no dups) - all BUT these // an unordered list of positive - just these, allowing dups // The numbering is 1-based; zero's are not allowed in the lists, nor are out-of-range. final int MAX_EQ2_COLS = 100000; // FIXME. Put this in a better spot. public Frame deepSlice( Object orows, Object ocols ) { // ocols is either a long[] or a Frame-of-1-Vec long[] cols; if( ocols == null ) { cols = (long[])ocols; assert cols == null; } else { if (ocols instanceof long[]) { cols = (long[])ocols; } else if (ocols instanceof Frame) { Frame fr = (Frame) ocols; if (fr.numCols() != 1) { throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)"); } long n = fr.anyVec().length(); if (n > MAX_EQ2_COLS) { throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")"); } cols = new long[(int)n]; Vec v = fr._vecs[0]; for (long i = 0; i < v.length(); i++) { cols[(int)i] = v.at8(i); } } else { throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")"); } } // Since cols is probably short convert to a positive list. int c2[] = null; if( cols==null ) { c2 = new int[numCols()]; for( int i=0; i<c2.length; i++ ) c2[i]=i; } else if( cols.length==0 ) { c2 = new int[0]; } else if( cols[0] > 0 ) { c2 = new int[cols.length]; for( int i=0; i<cols.length; i++ ) c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based } else { c2 = new int[numCols()-cols.length]; int j=0; for( int i=0; i<numCols(); i++ ) { if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i; else j++; } } for( int i=0; i<c2.length; i++ ) if( c2[i] >= numCols() ) throw new IllegalArgumentException("Trying to select column "+c2[i]+" but only "+numCols()+" present."); if( c2.length==0 ) throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)"); // Do Da Slice // orows is either a long[] or a Vec if (orows == null) return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2)); else if (orows instanceof long[]) { final long CHK_ROWS=1000000; long[] rows = (long[])orows; if (rows.length==0) return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2)); // Vec'ize the index array AppendableVec av = new AppendableVec("rownames"); int r = 0; int c = 0; while (r < rows.length) { NewChunk nc = new NewChunk(av, c); long end = Math.min(r+CHK_ROWS, rows.length); for (; r < end; r++) { nc.addNum(rows[r]); } nc.close(c++, null); } Vec c0 = av.close(null); // c0 is the row index vec - return new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0})) + Frame fr2 = new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0})) .outputFrame(names(c2), domains(c2)); - //return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2)); + UKV.remove(c0._key); // Remove hidden vector + return fr2; } Frame frows = (Frame)orows; Vec vrows = frows.anyVec(); // It's a compatible Vec; use it as boolean selector. // Build column names for the result. Vec [] vecs = new Vec[c2.length+1]; String [] names = new String[c2.length+1]; for(int i = 0; i < c2.length; ++i){ vecs[i] = _vecs[c2[i]]; names[i] = _names[c2[i]]; } vecs[c2.length] = vrows; names[c2.length] = "predicate"; return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2)); } // Slice and return in the form of new chunks. private static class Slice extends MRTask2<Slice> { final Frame _base; // the base frame to slice from final int[] _cols; Slice(int[] cols, Frame base) { _cols = cols; _base = base; } @Override public void map(Chunk[] ix, NewChunk[] ncs) { final Vec[] vecs = new Vec[_cols.length]; final Vec anyv = _base.anyVec(); final long nrow = anyv.length(); long r = ix[0].at80(0); int last_ci = anyv.elem2ChunkIdx(r<nrow?r:0); // memoize the last chunk index long last_c0 = anyv._espc[last_ci]; // ... last chunk start long last_c1 = anyv._espc[last_ci + 1]; // ... last chunk end Chunk[] last_cs = new Chunk[vecs.length]; // ... last chunks for (int c = 0; c < _cols.length; c++) { vecs[c] = _base.vecs()[_cols[c]]; last_cs[c] = vecs[c].elem2BV(last_ci); } for (int i = 0; i < ix[0]._len; i++) { // select one row r = ix[0].at80(i) - 1; // next row to select if (r < 0) continue; if (r >= nrow) { for (int c = 0; c < vecs.length; c++) ncs[c].addNum(Double.NaN); } else { if (r < last_c0 || r >= last_c1) { last_ci = anyv.elem2ChunkIdx(r); last_c0 = anyv._espc[last_ci]; last_c1 = anyv._espc[last_ci + 1]; for (int c = 0; c < vecs.length; c++) last_cs[c] = vecs[c].elem2BV(last_ci); } for (int c = 0; c < vecs.length; c++) ncs[c].addNum(last_cs[c].at(r)); } } } } // Bulk (expensive) copy from 2nd cols into 1st cols. // Sliced by the given cols & rows private static class DeepSlice extends MRTask2<DeepSlice> { final int _cols[]; final long _rows[]; DeepSlice( long rows[], int cols[]) { _cols=cols; _rows=rows;} @Override public void map( Chunk chks[], NewChunk nchks[] ) { long rstart = chks[0]._start; int rlen = chks[0]._len; // Total row count int rx = 0; // Which row to in/ex-clude int rlo = 0; // Lo/Hi for this block of rows int rhi = rlen; while( true ) { // Still got rows to include? if( _rows != null ) { // Got a row selector? if( rx >= _rows.length ) break; // All done with row selections long r = _rows[rx++]-1;// Next row selector if( r < 0 ) { // Row exclusion long er = Math.abs(r) - 2; if ( er < rstart) continue; rlo = (int)(er + 1 - rstart); //TODO: handle jumbled row indices ( e.g. -c(1,5,3) ) while(rx < _rows.length && (_rows[rx] + 1 == _rows[rx - 1] && rlo < rlen)) { if(rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl(); rx++; rlo++; //Exclude consecutive rows } rhi = rx >= _rows.length ? rlen : (int)Math.abs(_rows[rx] - 1) - 2; if(rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl(); } else { // Positive row list? if( r < rstart ) continue; rlo = (int)(r-rstart); rhi = rlo+1; // Stop at the next row while( rx < _rows.length && (_rows[rx]-1-rstart)==rhi && rhi < rlen ) { rx++; rhi++; // Grab sequential rows } } } // Process this next set of rows // For all cols in the new set for( int i=0; i<_cols.length; i++ ) { Chunk oc = chks[_cols[i]]; NewChunk nc = nchks[ i ]; if( oc._vec.isInt() ) { // Slice on integer columns for( int j=rlo; j<rhi; j++ ) if( oc.isNA0(j) ) nc.addNA(); else nc.addNum(oc.at80(j),0); } else { // Slice on double columns for( int j=rlo; j<rhi; j++ ) nc.addNum(oc.at0(j)); } } rlo=rhi; if( _rows==null ) break; } } } private static class DeepSelect extends MRTask2<DeepSelect> { @Override public void map( Chunk chks[], NewChunk nchks[] ) { Chunk pred = chks[chks.length-1]; for(int i = 0; i < pred._len; ++i){ if(pred.at0(i) != 0) for(int j = 0; j < chks.length-1; ++j) nchks[j].addNum(chks[j].at0(i)); } } } // ------------------------------------------------------------------------------ public <Y extends Flow.PerRow<Y>> // Type parameter Flow.FlowPerRow<Y> // Return type of with() with // The method name ( Flow.PerRow<Y> pr ) // Arguments for with() { return new Flow.FlowPerRow<Y>(pr,new Flow.FlowFrame(this)); } public Flow.FlowFilter with( Flow.Filter fr ) { return new Flow.FlowFilter(fr,new Flow.FlowFrame(this)); } public Flow.FlowGroupBy with( Flow.GroupBy fr ) { return new Flow.FlowGroupBy(fr,new Flow.FlowFrame(this)); } }
false
true
public Frame deepSlice( Object orows, Object ocols ) { // ocols is either a long[] or a Frame-of-1-Vec long[] cols; if( ocols == null ) { cols = (long[])ocols; assert cols == null; } else { if (ocols instanceof long[]) { cols = (long[])ocols; } else if (ocols instanceof Frame) { Frame fr = (Frame) ocols; if (fr.numCols() != 1) { throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)"); } long n = fr.anyVec().length(); if (n > MAX_EQ2_COLS) { throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")"); } cols = new long[(int)n]; Vec v = fr._vecs[0]; for (long i = 0; i < v.length(); i++) { cols[(int)i] = v.at8(i); } } else { throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")"); } } // Since cols is probably short convert to a positive list. int c2[] = null; if( cols==null ) { c2 = new int[numCols()]; for( int i=0; i<c2.length; i++ ) c2[i]=i; } else if( cols.length==0 ) { c2 = new int[0]; } else if( cols[0] > 0 ) { c2 = new int[cols.length]; for( int i=0; i<cols.length; i++ ) c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based } else { c2 = new int[numCols()-cols.length]; int j=0; for( int i=0; i<numCols(); i++ ) { if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i; else j++; } } for( int i=0; i<c2.length; i++ ) if( c2[i] >= numCols() ) throw new IllegalArgumentException("Trying to select column "+c2[i]+" but only "+numCols()+" present."); if( c2.length==0 ) throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)"); // Do Da Slice // orows is either a long[] or a Vec if (orows == null) return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2)); else if (orows instanceof long[]) { final long CHK_ROWS=1000000; long[] rows = (long[])orows; if (rows.length==0) return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2)); // Vec'ize the index array AppendableVec av = new AppendableVec("rownames"); int r = 0; int c = 0; while (r < rows.length) { NewChunk nc = new NewChunk(av, c); long end = Math.min(r+CHK_ROWS, rows.length); for (; r < end; r++) { nc.addNum(rows[r]); } nc.close(c++, null); } Vec c0 = av.close(null); // c0 is the row index vec return new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0})) .outputFrame(names(c2), domains(c2)); //return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2)); } Frame frows = (Frame)orows; Vec vrows = frows.anyVec(); // It's a compatible Vec; use it as boolean selector. // Build column names for the result. Vec [] vecs = new Vec[c2.length+1]; String [] names = new String[c2.length+1]; for(int i = 0; i < c2.length; ++i){ vecs[i] = _vecs[c2[i]]; names[i] = _names[c2[i]]; } vecs[c2.length] = vrows; names[c2.length] = "predicate"; return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2)); }
public Frame deepSlice( Object orows, Object ocols ) { // ocols is either a long[] or a Frame-of-1-Vec long[] cols; if( ocols == null ) { cols = (long[])ocols; assert cols == null; } else { if (ocols instanceof long[]) { cols = (long[])ocols; } else if (ocols instanceof Frame) { Frame fr = (Frame) ocols; if (fr.numCols() != 1) { throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)"); } long n = fr.anyVec().length(); if (n > MAX_EQ2_COLS) { throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")"); } cols = new long[(int)n]; Vec v = fr._vecs[0]; for (long i = 0; i < v.length(); i++) { cols[(int)i] = v.at8(i); } } else { throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")"); } } // Since cols is probably short convert to a positive list. int c2[] = null; if( cols==null ) { c2 = new int[numCols()]; for( int i=0; i<c2.length; i++ ) c2[i]=i; } else if( cols.length==0 ) { c2 = new int[0]; } else if( cols[0] > 0 ) { c2 = new int[cols.length]; for( int i=0; i<cols.length; i++ ) c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based } else { c2 = new int[numCols()-cols.length]; int j=0; for( int i=0; i<numCols(); i++ ) { if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i; else j++; } } for( int i=0; i<c2.length; i++ ) if( c2[i] >= numCols() ) throw new IllegalArgumentException("Trying to select column "+c2[i]+" but only "+numCols()+" present."); if( c2.length==0 ) throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)"); // Do Da Slice // orows is either a long[] or a Vec if (orows == null) return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2)); else if (orows instanceof long[]) { final long CHK_ROWS=1000000; long[] rows = (long[])orows; if (rows.length==0) return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2)); // Vec'ize the index array AppendableVec av = new AppendableVec("rownames"); int r = 0; int c = 0; while (r < rows.length) { NewChunk nc = new NewChunk(av, c); long end = Math.min(r+CHK_ROWS, rows.length); for (; r < end; r++) { nc.addNum(rows[r]); } nc.close(c++, null); } Vec c0 = av.close(null); // c0 is the row index vec Frame fr2 = new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0})) .outputFrame(names(c2), domains(c2)); UKV.remove(c0._key); // Remove hidden vector return fr2; } Frame frows = (Frame)orows; Vec vrows = frows.anyVec(); // It's a compatible Vec; use it as boolean selector. // Build column names for the result. Vec [] vecs = new Vec[c2.length+1]; String [] names = new String[c2.length+1]; for(int i = 0; i < c2.length; ++i){ vecs[i] = _vecs[c2[i]]; names[i] = _names[c2[i]]; } vecs[c2.length] = vrows; names[c2.length] = "predicate"; return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2)); }
diff --git a/maven-embedder/src/main/java/org/apache/maven/embedder/MavenEmbedder.java b/maven-embedder/src/main/java/org/apache/maven/embedder/MavenEmbedder.java index 547ad2a25..d7fcce78f 100644 --- a/maven-embedder/src/main/java/org/apache/maven/embedder/MavenEmbedder.java +++ b/maven-embedder/src/main/java/org/apache/maven/embedder/MavenEmbedder.java @@ -1,736 +1,736 @@ package org.apache.maven.embedder; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.BuildFailureException; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.ArtifactRepositoryPolicy; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ReactorManager; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.lifecycle.LifecycleExecutor; import org.apache.maven.model.Model; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.monitor.event.DefaultEventDispatcher; import org.apache.maven.monitor.event.EventDispatcher; import org.apache.maven.monitor.event.EventMonitor; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.DuplicateProjectException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.RuntimeInfo; import org.apache.maven.settings.Settings; import org.apache.maven.wagon.events.TransferListener; import org.codehaus.classworlds.ClassWorld; import org.codehaus.classworlds.DuplicateRealmException; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.component.repository.ComponentDescriptor; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.configuration.PlexusConfigurationException; import org.codehaus.plexus.embed.Embedder; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.dag.CycleDetectedException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; /** * Class intended to be used by clients who wish to embed Maven into their applications * * @author <a href="mailto:[email protected]">Jason van Zyl</a> */ public class MavenEmbedder { public static final String userHome = System.getProperty( "user.home" ); // ---------------------------------------------------------------------- // Embedder // ---------------------------------------------------------------------- private Embedder embedder; // ---------------------------------------------------------------------- // Components // ---------------------------------------------------------------------- private MavenProjectBuilder mavenProjectBuilder; private ArtifactRepositoryFactory artifactRepositoryFactory; private MavenSettingsBuilder settingsBuilder; private LifecycleExecutor lifecycleExecutor; private WagonManager wagonManager; private MavenXpp3Reader modelReader; private MavenXpp3Writer modelWriter; private ProfileManager profileManager; private PluginDescriptorBuilder pluginDescriptorBuilder; private ArtifactFactory artifactFactory; private ArtifactResolver artifactResolver; private ArtifactRepositoryLayout defaultArtifactRepositoryLayout; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- private Settings settings; private ArtifactRepository localRepository; private File localRepositoryDirectory; private ClassLoader classLoader; private MavenEmbedderLogger logger; // ---------------------------------------------------------------------- // User options // ---------------------------------------------------------------------- // release plugin uses this but in IDE there will probably always be some form of interaction. private boolean interactiveMode; private boolean offline; private String globalChecksumPolicy; /** * This option determines whether the embedder is to be aligned to the user * installation. */ private boolean alignWithUserInstallation; // ---------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------- public void setInteractiveMode( boolean interactiveMode ) { this.interactiveMode = interactiveMode; } public boolean isInteractiveMode() { return interactiveMode; } public void setOffline( boolean offline ) { this.offline = offline; } public boolean isOffline() { return offline; } public void setGlobalChecksumPolicy( String globalChecksumPolicy ) { this.globalChecksumPolicy = globalChecksumPolicy; } public String getGlobalChecksumPolicy() { return globalChecksumPolicy; } public boolean isAlignWithUserInstallation() { return alignWithUserInstallation; } public void setAlignWithUserInstallation( boolean alignWithUserInstallation ) { this.alignWithUserInstallation = alignWithUserInstallation; } /** * Set the classloader to use with the maven embedder. * * @param classLoader */ public void setClassLoader( ClassLoader classLoader ) { this.classLoader = classLoader; } public ClassLoader getClassLoader() { return classLoader; } public void setLocalRepositoryDirectory( File localRepositoryDirectory ) { this.localRepositoryDirectory = localRepositoryDirectory; } public File getLocalRepositoryDirectory() { return localRepositoryDirectory; } public ArtifactRepository getLocalRepository() { return localRepository; } public MavenEmbedderLogger getLogger() { return logger; } public void setLogger( MavenEmbedderLogger logger ) { this.logger = logger; } // ---------------------------------------------------------------------- // Embedder Client Contract // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Model // ---------------------------------------------------------------------- public Model readModel( File model ) throws XmlPullParserException, FileNotFoundException, IOException { return modelReader.read( new FileReader( model ) ); } public void writeModel( Writer writer, Model model ) throws IOException { modelWriter.write( writer, model ); } // ---------------------------------------------------------------------- // Project // ---------------------------------------------------------------------- public MavenProject readProject( File mavenProject ) throws ProjectBuildingException { return mavenProjectBuilder.build( mavenProject, localRepository, profileManager ); } public MavenProject readProjectWithDependencies( File mavenProject, TransferListener transferListener ) throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException { return mavenProjectBuilder.buildWithDependencies( mavenProject, localRepository, profileManager, transferListener ); } public MavenProject readProjectWithDependencies( File mavenProject ) throws ProjectBuildingException, ArtifactResolutionException, ArtifactNotFoundException { return mavenProjectBuilder.buildWithDependencies( mavenProject, localRepository, profileManager ); } public List collectProjects( File basedir, String[] includes, String[] excludes ) throws MojoExecutionException { List projects = new ArrayList(); List poms = getPomFiles( basedir, includes, excludes ); for ( Iterator i = poms.iterator(); i.hasNext(); ) { File pom = (File) i.next(); try { MavenProject p = readProject( pom ); projects.add( p ); } catch ( ProjectBuildingException e ) { throw new MojoExecutionException( "Error loading " + pom, e ); } } return projects; } // ---------------------------------------------------------------------- // Artifacts // ---------------------------------------------------------------------- public Artifact createArtifact( String groupId, String artifactId, String version, String scope, String type ) { return artifactFactory.createArtifact( groupId, artifactId, version, scope, type ); } public Artifact createArtifactWithClassifier( String groupId, String artifactId, String version, String type, String classifier ) { return artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, type, classifier ); } public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository ) throws ArtifactResolutionException, ArtifactNotFoundException { artifactResolver.resolve( artifact, remoteRepositories, localRepository ); } // ---------------------------------------------------------------------- // Plugins // ---------------------------------------------------------------------- public List getAvailablePlugins() { List plugins = new ArrayList(); plugins.add( makeMockPlugin( "org.apache.maven.plugins", "maven-jar-plugin", "Maven Jar Plug-in" ) ); plugins.add( makeMockPlugin( "org.apache.maven.plugins", "maven-compiler-plugin", "Maven Compiler Plug-in" ) ); return plugins; } public PluginDescriptor getPluginDescriptor( SummaryPluginDescriptor summaryPluginDescriptor ) throws MavenEmbedderException { PluginDescriptor pluginDescriptor; try { InputStream is = classLoader.getResourceAsStream( "/plugins/" + summaryPluginDescriptor.getArtifactId() + ".xml" ); pluginDescriptor = pluginDescriptorBuilder.build( new InputStreamReader( is ) ); } catch ( PlexusConfigurationException e ) { throw new MavenEmbedderException( "Error retrieving plugin descriptor.", e ); } return pluginDescriptor; } private SummaryPluginDescriptor makeMockPlugin( String groupId, String artifactId, String name ) { return new SummaryPluginDescriptor( groupId, artifactId, name ); } // ---------------------------------------------------------------------- // Execution of phases/goals // ---------------------------------------------------------------------- // TODO: should we allow the passing in of a settings object so that everything can be taken from the client env // TODO: transfer listener // TODO: logger public void execute( MavenProject project, List goals, EventMonitor eventMonitor, TransferListener transferListener, Properties properties, File executionRootDirectory ) throws CycleDetectedException, LifecycleExecutionException, BuildFailureException, DuplicateProjectException { execute( Collections.singletonList( project ), goals, eventMonitor, transferListener, properties, executionRootDirectory ); } public void execute( List projects, List goals, EventMonitor eventMonitor, TransferListener transferListener, Properties properties, File executionRootDirectory ) throws CycleDetectedException, LifecycleExecutionException, BuildFailureException, DuplicateProjectException { ReactorManager rm = new ReactorManager( projects ); EventDispatcher eventDispatcher = new DefaultEventDispatcher(); eventDispatcher.addEventMonitor( eventMonitor ); // If this option is set the exception seems to be hidden ... //rm.setFailureBehavior( ReactorManager.FAIL_AT_END ); rm.setFailureBehavior( ReactorManager.FAIL_FAST ); MavenSession session = new MavenSession( embedder.getContainer(), settings, localRepository, eventDispatcher, rm, goals, executionRootDirectory.getAbsolutePath(), properties, new Date() ); session.setUsingPOMsFromFilesystem( true ); if ( transferListener != null ) { wagonManager.setDownloadMonitor( transferListener ); } // ---------------------------------------------------------------------- // Maven should not be using system properties internally but because // it does for now I'll just take properties that are handed to me // and set them so that the plugin expression evaluator will work // as expected. // ---------------------------------------------------------------------- if ( properties != null ) { for ( Iterator i = properties.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); String value = properties.getProperty( key ); System.setProperty( key, value ); } } lifecycleExecutor.execute( session, rm, session.getEventDispatcher() ); } // ---------------------------------------------------------------------- // Lifecycle information // ---------------------------------------------------------------------- public List getLifecyclePhases() throws MavenEmbedderException { List phases = new ArrayList(); ComponentDescriptor descriptor = embedder.getContainer().getComponentDescriptor( LifecycleExecutor.ROLE ); PlexusConfiguration configuration = descriptor.getConfiguration(); PlexusConfiguration[] phasesConfigurations = configuration.getChild( "lifecycles" ).getChild( 0 ).getChild( "phases" ).getChildren( "phase" ); try { for ( int i = 0; i < phasesConfigurations.length; i++ ) { phases.add( phasesConfigurations[i].getValue() ); } } catch ( PlexusConfigurationException e ) { throw new MavenEmbedderException( "Cannot retrieve default lifecycle phasesConfigurations.", e ); } return phases; } // ---------------------------------------------------------------------- // Remote Repository // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Local Repository // ---------------------------------------------------------------------- public static final String DEFAULT_LOCAL_REPO_ID = "local"; public static final String DEFAULT_LAYOUT_ID = "default"; public ArtifactRepository createLocalRepository( File localRepository ) throws ComponentLookupException { return createLocalRepository( localRepository.getAbsolutePath(), DEFAULT_LOCAL_REPO_ID ); } public ArtifactRepository createLocalRepository( Settings settings ) throws ComponentLookupException { return createLocalRepository( settings.getLocalRepository(), DEFAULT_LOCAL_REPO_ID ); } public ArtifactRepository createLocalRepository( String url, String repositoryId ) throws ComponentLookupException { if ( !url.startsWith( "file:" ) ) { url = "file://" + url; } return createRepository( url, repositoryId ); } public ArtifactRepository createRepository( String url, String repositoryId ) throws ComponentLookupException { // snapshots vs releases // offline = to turning the update policy off //TODO: we'll need to allow finer grained creation of repositories but this will do for now String updatePolicyFlag = ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS; String checksumPolicyFlag = ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN; ArtifactRepositoryPolicy snapshotsPolicy = new ArtifactRepositoryPolicy( true, updatePolicyFlag, checksumPolicyFlag ); ArtifactRepositoryPolicy releasesPolicy = new ArtifactRepositoryPolicy( true, updatePolicyFlag, checksumPolicyFlag ); return artifactRepositoryFactory.createArtifactRepository( repositoryId, url, defaultArtifactRepositoryLayout, snapshotsPolicy, releasesPolicy ); } // ---------------------------------------------------------------------- // Internal utility code // ---------------------------------------------------------------------- private RuntimeInfo createRuntimeInfo( Settings settings ) { RuntimeInfo runtimeInfo = new RuntimeInfo( settings ); runtimeInfo.setPluginUpdateOverride( Boolean.FALSE ); return runtimeInfo; } private List getPomFiles( File basedir, String[] includes, String[] excludes ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( basedir ); scanner.setIncludes( includes ); scanner.setExcludes( excludes ); scanner.scan(); List poms = new ArrayList(); for ( int i = 0; i < scanner.getIncludedFiles().length; i++ ) { poms.add( new File( basedir, scanner.getIncludedFiles()[i] ) ); } return poms; } // ---------------------------------------------------------------------- // Lifecycle // ---------------------------------------------------------------------- public void start() throws MavenEmbedderException { detectUserInstallation(); // ---------------------------------------------------------------------- // Set the maven.home system property which is need by components like // the plugin registry builder. // ---------------------------------------------------------------------- if ( classLoader == null ) { throw new IllegalStateException( "A classloader must be specified using setClassLoader(ClassLoader)." ); } embedder = new Embedder(); if ( logger != null ) { embedder.setLoggerManager( new MavenEmbedderLoggerManager( new PlexusLoggerAdapter( logger ) ) ); } try { ClassWorld classWorld = new ClassWorld(); classWorld.newRealm( "plexus.core", classLoader ); embedder.start( classWorld ); // ---------------------------------------------------------------------- // Lookup each of the components we need to provide the desired // client interface. // ---------------------------------------------------------------------- modelReader = new MavenXpp3Reader(); modelWriter = new MavenXpp3Writer(); pluginDescriptorBuilder = new PluginDescriptorBuilder(); profileManager = new DefaultProfileManager( embedder.getContainer() ); mavenProjectBuilder = (MavenProjectBuilder) embedder.lookup( MavenProjectBuilder.ROLE ); // ---------------------------------------------------------------------- // Artifact related components // ---------------------------------------------------------------------- artifactRepositoryFactory = (ArtifactRepositoryFactory) embedder.lookup( ArtifactRepositoryFactory.ROLE ); artifactFactory = (ArtifactFactory) embedder.lookup( ArtifactFactory.ROLE ); artifactResolver = (ArtifactResolver) embedder.lookup( ArtifactResolver.ROLE ); defaultArtifactRepositoryLayout = (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.ROLE, DEFAULT_LAYOUT_ID ); lifecycleExecutor = (LifecycleExecutor) embedder.lookup( LifecycleExecutor.ROLE ); wagonManager = (WagonManager) embedder.lookup( WagonManager.ROLE ); createMavenSettings(); - profileManager.loadSettingsProfile( settings ); + profileManager.loadSettingsProfiles( settings ); localRepository = createLocalRepository( settings ); } catch ( PlexusContainerException e ) { throw new MavenEmbedderException( "Cannot start Plexus embedder.", e ); } catch ( DuplicateRealmException e ) { throw new MavenEmbedderException( "Cannot create Classworld realm for the embedder.", e ); } catch ( ComponentLookupException e ) { throw new MavenEmbedderException( "Cannot lookup required component.", e ); } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void detectUserInstallation() { if ( new File( userHome, ".m2" ).exists() ) { alignWithUserInstallation = true; } } /** * Create the Settings that will be used with the embedder. If we are aligning with the user * installation then we lookup the standard settings builder and use that to create our * settings. Otherwise we constructs a settings object and populate the information * ourselves. * * @throws MavenEmbedderException * @throws ComponentLookupException */ private void createMavenSettings() throws MavenEmbedderException, ComponentLookupException { if ( alignWithUserInstallation ) { // ---------------------------------------------------------------------- // We will use the standard method for creating the settings. This // method reproduces the method of building the settings from the CLI // mode of operation. // ---------------------------------------------------------------------- settingsBuilder = (MavenSettingsBuilder) embedder.lookup( MavenSettingsBuilder.ROLE ); try { settings = settingsBuilder.buildSettings(); } catch ( IOException e ) { throw new MavenEmbedderException( "Error creating settings.", e ); } catch ( XmlPullParserException e ) { throw new MavenEmbedderException( "Error creating settings.", e ); } } else { if ( localRepository == null ) { throw new IllegalArgumentException( "When not aligning with a user install you must specify a local repository location using the setLocalRepositoryDirectory( File ) method." ); } settings = new Settings(); settings.setLocalRepository( localRepositoryDirectory.getAbsolutePath() ); settings.setRuntimeInfo( createRuntimeInfo( settings ) ); settings.setOffline( offline ); settings.setInteractiveMode( interactiveMode ); } } // ---------------------------------------------------------------------- // Lifecycle // ---------------------------------------------------------------------- public void stop() throws MavenEmbedderException { try { embedder.release( mavenProjectBuilder ); embedder.release( artifactRepositoryFactory ); embedder.release( settingsBuilder ); embedder.release( lifecycleExecutor ); } catch ( ComponentLifecycleException e ) { throw new MavenEmbedderException( "Cannot stop the embedder.", e ); } } }
true
true
public void start() throws MavenEmbedderException { detectUserInstallation(); // ---------------------------------------------------------------------- // Set the maven.home system property which is need by components like // the plugin registry builder. // ---------------------------------------------------------------------- if ( classLoader == null ) { throw new IllegalStateException( "A classloader must be specified using setClassLoader(ClassLoader)." ); } embedder = new Embedder(); if ( logger != null ) { embedder.setLoggerManager( new MavenEmbedderLoggerManager( new PlexusLoggerAdapter( logger ) ) ); } try { ClassWorld classWorld = new ClassWorld(); classWorld.newRealm( "plexus.core", classLoader ); embedder.start( classWorld ); // ---------------------------------------------------------------------- // Lookup each of the components we need to provide the desired // client interface. // ---------------------------------------------------------------------- modelReader = new MavenXpp3Reader(); modelWriter = new MavenXpp3Writer(); pluginDescriptorBuilder = new PluginDescriptorBuilder(); profileManager = new DefaultProfileManager( embedder.getContainer() ); mavenProjectBuilder = (MavenProjectBuilder) embedder.lookup( MavenProjectBuilder.ROLE ); // ---------------------------------------------------------------------- // Artifact related components // ---------------------------------------------------------------------- artifactRepositoryFactory = (ArtifactRepositoryFactory) embedder.lookup( ArtifactRepositoryFactory.ROLE ); artifactFactory = (ArtifactFactory) embedder.lookup( ArtifactFactory.ROLE ); artifactResolver = (ArtifactResolver) embedder.lookup( ArtifactResolver.ROLE ); defaultArtifactRepositoryLayout = (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.ROLE, DEFAULT_LAYOUT_ID ); lifecycleExecutor = (LifecycleExecutor) embedder.lookup( LifecycleExecutor.ROLE ); wagonManager = (WagonManager) embedder.lookup( WagonManager.ROLE ); createMavenSettings(); profileManager.loadSettingsProfile( settings ); localRepository = createLocalRepository( settings ); } catch ( PlexusContainerException e ) { throw new MavenEmbedderException( "Cannot start Plexus embedder.", e ); } catch ( DuplicateRealmException e ) { throw new MavenEmbedderException( "Cannot create Classworld realm for the embedder.", e ); } catch ( ComponentLookupException e ) { throw new MavenEmbedderException( "Cannot lookup required component.", e ); } }
public void start() throws MavenEmbedderException { detectUserInstallation(); // ---------------------------------------------------------------------- // Set the maven.home system property which is need by components like // the plugin registry builder. // ---------------------------------------------------------------------- if ( classLoader == null ) { throw new IllegalStateException( "A classloader must be specified using setClassLoader(ClassLoader)." ); } embedder = new Embedder(); if ( logger != null ) { embedder.setLoggerManager( new MavenEmbedderLoggerManager( new PlexusLoggerAdapter( logger ) ) ); } try { ClassWorld classWorld = new ClassWorld(); classWorld.newRealm( "plexus.core", classLoader ); embedder.start( classWorld ); // ---------------------------------------------------------------------- // Lookup each of the components we need to provide the desired // client interface. // ---------------------------------------------------------------------- modelReader = new MavenXpp3Reader(); modelWriter = new MavenXpp3Writer(); pluginDescriptorBuilder = new PluginDescriptorBuilder(); profileManager = new DefaultProfileManager( embedder.getContainer() ); mavenProjectBuilder = (MavenProjectBuilder) embedder.lookup( MavenProjectBuilder.ROLE ); // ---------------------------------------------------------------------- // Artifact related components // ---------------------------------------------------------------------- artifactRepositoryFactory = (ArtifactRepositoryFactory) embedder.lookup( ArtifactRepositoryFactory.ROLE ); artifactFactory = (ArtifactFactory) embedder.lookup( ArtifactFactory.ROLE ); artifactResolver = (ArtifactResolver) embedder.lookup( ArtifactResolver.ROLE ); defaultArtifactRepositoryLayout = (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.ROLE, DEFAULT_LAYOUT_ID ); lifecycleExecutor = (LifecycleExecutor) embedder.lookup( LifecycleExecutor.ROLE ); wagonManager = (WagonManager) embedder.lookup( WagonManager.ROLE ); createMavenSettings(); profileManager.loadSettingsProfiles( settings ); localRepository = createLocalRepository( settings ); } catch ( PlexusContainerException e ) { throw new MavenEmbedderException( "Cannot start Plexus embedder.", e ); } catch ( DuplicateRealmException e ) { throw new MavenEmbedderException( "Cannot create Classworld realm for the embedder.", e ); } catch ( ComponentLookupException e ) { throw new MavenEmbedderException( "Cannot lookup required component.", e ); } }
diff --git a/reflens-core/src/main/java/org/grouplens/reflens/baseline/ItemMeanPredictor.java b/reflens-core/src/main/java/org/grouplens/reflens/baseline/ItemMeanPredictor.java index 8db2d21f5..f59bee8be 100644 --- a/reflens-core/src/main/java/org/grouplens/reflens/baseline/ItemMeanPredictor.java +++ b/reflens-core/src/main/java/org/grouplens/reflens/baseline/ItemMeanPredictor.java @@ -1,164 +1,163 @@ /* * RefLens, a reference implementation of recommender algorithms. * Copyright 2010 Michael Ekstrand <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and * to copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms * and conditions of the license of that module. An independent module is a * module which is not derived from or based on this library. If you modify this * library, you may extend this exception to your version of the library, but * you are not obligated to do so. If you do not wish to do so, delete this * exception statement from your version. */ /** * */ package org.grouplens.reflens.baseline; import it.unimi.dsi.fastutil.longs.Long2DoubleMap; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2IntMap; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import it.unimi.dsi.fastutil.longs.LongCollection; import it.unimi.dsi.fastutil.longs.LongIterator; import java.util.Collection; import java.util.Map; import org.grouplens.reflens.RatingPredictor; import org.grouplens.reflens.RatingPredictorBuilder; import org.grouplens.reflens.data.Cursor; import org.grouplens.reflens.data.Rating; import org.grouplens.reflens.data.RatingDataSource; import org.grouplens.reflens.data.ScoredId; import org.grouplens.reflens.util.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Rating predictor that returns the item's mean rating for all predictions. * * If the item has no ratings, the global mean rating is returned. * * This implements the baseline predictor <i>p<sub>u,i</sub> = µ + b<sub>i</sub></i>, * where <i>b<sub>i</sub></i> is the item's average rating (less the global * mean µ). * * @author Michael Ekstrand <[email protected]> * */ public class ItemMeanPredictor implements RatingPredictor { private final Long2DoubleMap itemAverages; private final double globalMean; protected ItemMeanPredictor(double mean, Long2DoubleMap means) { globalMean = mean; itemAverages = means; } /* (non-Javadoc) * @see org.grouplens.reflens.RatingPredictor#predict(long, java.util.Map, java.util.Collection) */ @Override public Map<Long, Double> predict(long user, Map<Long, Double> ratings, Collection<Long> items) { Long2DoubleMap predictions = new Long2DoubleOpenHashMap(items.size()); LongCollection fitems = CollectionUtils.getFastCollection(items); LongIterator iter = fitems.iterator(); while (iter.hasNext()) { long iid = iter.nextLong(); predictions.put(iid, getItemMean(iid)); } return predictions; } /* (non-Javadoc) * @see org.grouplens.reflens.RatingPredictor#predict(long, java.util.Map, long) */ @Override public ScoredId predict(long user, Map<Long, Double> ratings, long item) { return new ScoredId(item, getItemMean(item)); } protected double getItemMean(long id) { return globalMean + itemAverages.get(id); } /** * Predictor builder for the item mean predictor. * @author Michael Ekstrand <[email protected]> * */ public static class Builder implements RatingPredictorBuilder { private static Logger logger = LoggerFactory.getLogger(Builder.class); @Override public RatingPredictor build(RatingDataSource data) { // We iterate the loop to compute the global and per-item mean // ratings. Subtracting the global mean from each per-item mean // is equivalent to averaging the offsets from the global mean, so // we can compute the means in parallel and subtract after a single // pass through the data. double total = 0.0; int count = 0; Long2DoubleMap itemTotals = new Long2DoubleOpenHashMap(); itemTotals.defaultReturnValue(0.0); Long2IntMap itemCounts = new Long2IntOpenHashMap(); itemCounts.defaultReturnValue(0); Cursor<Rating> ratings = data.getRatings(); try { for (Rating r: ratings) { long i = r.getItemId(); double v = r.getRating(); total += v; count++; itemTotals.put(i, v + itemTotals.get(i)); itemCounts.put(i, 1 + itemCounts.get(i)); } } finally { ratings.close(); } double mean = 0.0; if (count > 0) mean = total / count; logger.debug("Computed global mean {} for {} items", mean, itemTotals.size()); LongIterator items = itemTotals.keySet().iterator(); while (items.hasNext()) { long iid = items.nextLong(); int ct = itemCounts.get(iid); double t = itemTotals.get(iid); double avg = 0.0; - if (ct > 0) avg = t / ct; - avg = avg - mean; + if (ct > 0) avg = t / ct - mean; itemTotals.put(iid, avg); } return create(count > 0 ? total / count : 0.0, itemTotals); } protected RatingPredictor create(double globalMean, Long2DoubleMap itemMeans) { return new ItemMeanPredictor(globalMean, itemMeans); } } }
true
true
public RatingPredictor build(RatingDataSource data) { // We iterate the loop to compute the global and per-item mean // ratings. Subtracting the global mean from each per-item mean // is equivalent to averaging the offsets from the global mean, so // we can compute the means in parallel and subtract after a single // pass through the data. double total = 0.0; int count = 0; Long2DoubleMap itemTotals = new Long2DoubleOpenHashMap(); itemTotals.defaultReturnValue(0.0); Long2IntMap itemCounts = new Long2IntOpenHashMap(); itemCounts.defaultReturnValue(0); Cursor<Rating> ratings = data.getRatings(); try { for (Rating r: ratings) { long i = r.getItemId(); double v = r.getRating(); total += v; count++; itemTotals.put(i, v + itemTotals.get(i)); itemCounts.put(i, 1 + itemCounts.get(i)); } } finally { ratings.close(); } double mean = 0.0; if (count > 0) mean = total / count; logger.debug("Computed global mean {} for {} items", mean, itemTotals.size()); LongIterator items = itemTotals.keySet().iterator(); while (items.hasNext()) { long iid = items.nextLong(); int ct = itemCounts.get(iid); double t = itemTotals.get(iid); double avg = 0.0; if (ct > 0) avg = t / ct; avg = avg - mean; itemTotals.put(iid, avg); } return create(count > 0 ? total / count : 0.0, itemTotals); }
public RatingPredictor build(RatingDataSource data) { // We iterate the loop to compute the global and per-item mean // ratings. Subtracting the global mean from each per-item mean // is equivalent to averaging the offsets from the global mean, so // we can compute the means in parallel and subtract after a single // pass through the data. double total = 0.0; int count = 0; Long2DoubleMap itemTotals = new Long2DoubleOpenHashMap(); itemTotals.defaultReturnValue(0.0); Long2IntMap itemCounts = new Long2IntOpenHashMap(); itemCounts.defaultReturnValue(0); Cursor<Rating> ratings = data.getRatings(); try { for (Rating r: ratings) { long i = r.getItemId(); double v = r.getRating(); total += v; count++; itemTotals.put(i, v + itemTotals.get(i)); itemCounts.put(i, 1 + itemCounts.get(i)); } } finally { ratings.close(); } double mean = 0.0; if (count > 0) mean = total / count; logger.debug("Computed global mean {} for {} items", mean, itemTotals.size()); LongIterator items = itemTotals.keySet().iterator(); while (items.hasNext()) { long iid = items.nextLong(); int ct = itemCounts.get(iid); double t = itemTotals.get(iid); double avg = 0.0; if (ct > 0) avg = t / ct - mean; itemTotals.put(iid, avg); } return create(count > 0 ? total / count : 0.0, itemTotals); }
diff --git a/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandleCommand.java b/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandleCommand.java index 867e2f471a..370df68748 100644 --- a/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandleCommand.java +++ b/drools-core/src/main/java/org/drools/command/runtime/rule/GetFactHandleCommand.java @@ -1,57 +1,59 @@ /* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.command.runtime.rule; import org.drools.command.Context; import org.drools.command.impl.GenericCommand; import org.drools.command.impl.KnowledgeCommandContext; import org.drools.common.InternalFactHandle; import org.drools.runtime.StatefulKnowledgeSession; import org.drools.runtime.rule.FactHandle; public class GetFactHandleCommand implements GenericCommand<FactHandle> { private Object object; private boolean disconnected; public GetFactHandleCommand(Object object) { this.object = object; this.disconnected = false; } public GetFactHandleCommand(Object object, boolean disconnected) { this.object = object; this.disconnected = disconnected; } public FactHandle execute(Context context) { StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession(); InternalFactHandle factHandle = (InternalFactHandle) ksession.getFactHandle( object ); - if ( factHandle != null && disconnected){ + if ( factHandle != null ){ InternalFactHandle handle = factHandle.clone(); - handle.disconnect(); + if ( disconnected ) { + handle.disconnect(); + } return handle; } return null; } public String toString() { return "ksession.getFactHandle( " + object + " );"; } }
false
true
public FactHandle execute(Context context) { StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession(); InternalFactHandle factHandle = (InternalFactHandle) ksession.getFactHandle( object ); if ( factHandle != null && disconnected){ InternalFactHandle handle = factHandle.clone(); handle.disconnect(); return handle; } return null; }
public FactHandle execute(Context context) { StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession(); InternalFactHandle factHandle = (InternalFactHandle) ksession.getFactHandle( object ); if ( factHandle != null ){ InternalFactHandle handle = factHandle.clone(); if ( disconnected ) { handle.disconnect(); } return handle; } return null; }
diff --git a/javafx.refactoring/src/org/netbeans/modules/javafx/refactoring/impl/WhereUsedElement.java b/javafx.refactoring/src/org/netbeans/modules/javafx/refactoring/impl/WhereUsedElement.java index 7ccd80ca..825717df 100644 --- a/javafx.refactoring/src/org/netbeans/modules/javafx/refactoring/impl/WhereUsedElement.java +++ b/javafx.refactoring/src/org/netbeans/modules/javafx/refactoring/impl/WhereUsedElement.java @@ -1,177 +1,177 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.refactoring.impl; import com.sun.javafx.api.tree.JavaFXTreePath; import java.io.IOException; import javax.swing.text.BadLocationException; import javax.swing.text.Position.Bias; import javax.swing.text.StyledDocument; import org.netbeans.api.javafx.lexer.JFXTokenId; import org.netbeans.api.javafx.source.CompilationController; import org.netbeans.api.javafx.source.JavaFXSource; import org.netbeans.api.javafx.source.Task; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.editor.GuardedDocument; import org.netbeans.editor.Utilities; import org.netbeans.modules.javafx.refactoring.impl.javafxc.SourceUtils; import org.netbeans.modules.javafx.refactoring.impl.javafxc.TreePathHandle; import org.netbeans.modules.refactoring.spi.SimpleRefactoringElementImplementation; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.text.DataEditorSupport; import org.openide.text.NbDocument; import org.openide.text.PositionBounds; import org.openide.util.Lookup; /** * An element in the refactoring preview list which holds information about the find-usages-match * * @author Jaroslav Bachorik */ public class WhereUsedElement extends SimpleRefactoringElementImplementation { private PositionBounds bounds; private String displayText; volatile private int startPosition; volatile private int endPosition; private DataEditorSupport des; private GuardedDocument doc; private final TreePathHandle handle; private final Lookup context; private WhereUsedElement(TreePathHandle handle, Lookup context) throws IOException { this.handle = handle; this.context = context; init(); } private void init() throws IOException { DataObject dobj = DataObject.find(handle.getFileObject()); des = (DataEditorSupport)dobj.getCookie(EditorCookie.class); doc = (GuardedDocument)des.getDocument(); if (doc == null) { doc = (GuardedDocument)des.openDocument(); } JavaFXSource jfxs = JavaFXSource.forFileObject(handle.getFileObject()); jfxs.runWhenScanFinished(new Task<CompilationController>() { public void run(CompilationController cc) throws Exception { JavaFXTreePath path = handle.resolve(cc); TokenSequence<JFXTokenId> tokens = cc.getTreeUtilities().tokensFor(path.getLeaf()); tokens.moveStart(); while (tokens.moveNext()) { Token<JFXTokenId> token = tokens.token(); if (handle.getSimpleName().equals(token.text().toString())) { startPosition = token.offset(cc.getTokenHierarchy()); endPosition = startPosition + token.length(); break; } } } }, true); try { doc.readLock(); if (startPosition != -1) { int sta = Utilities.getRowFirstNonWhite(doc, startPosition); if (sta == -1) { sta = Utilities.getRowStart(doc, startPosition); } int en = Utilities.getRowLastNonWhite(doc, startPosition); if (en == -1) { en = Utilities.getRowEnd(doc, startPosition); } else { // Last nonwhite - left side of the last char, not inclusive en++; } displayText = SourceUtils.getHtml(doc.getText(sta, en - sta + 1)); bounds = new PositionBounds(des.createPositionRef(startPosition, Bias.Forward), des.createPositionRef(endPosition, Bias.Forward)); } else { System.err.println("*** Can not resolve: " + handle); throw new IOException(); } } catch (BadLocationException e) { - throw new IOException(e); + throw new IOException(e.getLocalizedMessage()); } finally { doc.readUnlock(); } } public String getDisplayText() { return displayText; } public Lookup getLookup() { return context; } public PositionBounds getPosition() { return bounds; } public String getText() { return displayText; } public void performChange() { } public FileObject getParentFile() { return handle.getFileObject(); } public static WhereUsedElement create(TreePathHandle handle, Lookup context) { try { return new WhereUsedElement(handle, context); } catch (IOException e) { } return null; } }
true
true
private void init() throws IOException { DataObject dobj = DataObject.find(handle.getFileObject()); des = (DataEditorSupport)dobj.getCookie(EditorCookie.class); doc = (GuardedDocument)des.getDocument(); if (doc == null) { doc = (GuardedDocument)des.openDocument(); } JavaFXSource jfxs = JavaFXSource.forFileObject(handle.getFileObject()); jfxs.runWhenScanFinished(new Task<CompilationController>() { public void run(CompilationController cc) throws Exception { JavaFXTreePath path = handle.resolve(cc); TokenSequence<JFXTokenId> tokens = cc.getTreeUtilities().tokensFor(path.getLeaf()); tokens.moveStart(); while (tokens.moveNext()) { Token<JFXTokenId> token = tokens.token(); if (handle.getSimpleName().equals(token.text().toString())) { startPosition = token.offset(cc.getTokenHierarchy()); endPosition = startPosition + token.length(); break; } } } }, true); try { doc.readLock(); if (startPosition != -1) { int sta = Utilities.getRowFirstNonWhite(doc, startPosition); if (sta == -1) { sta = Utilities.getRowStart(doc, startPosition); } int en = Utilities.getRowLastNonWhite(doc, startPosition); if (en == -1) { en = Utilities.getRowEnd(doc, startPosition); } else { // Last nonwhite - left side of the last char, not inclusive en++; } displayText = SourceUtils.getHtml(doc.getText(sta, en - sta + 1)); bounds = new PositionBounds(des.createPositionRef(startPosition, Bias.Forward), des.createPositionRef(endPosition, Bias.Forward)); } else { System.err.println("*** Can not resolve: " + handle); throw new IOException(); } } catch (BadLocationException e) { throw new IOException(e); } finally { doc.readUnlock(); } }
private void init() throws IOException { DataObject dobj = DataObject.find(handle.getFileObject()); des = (DataEditorSupport)dobj.getCookie(EditorCookie.class); doc = (GuardedDocument)des.getDocument(); if (doc == null) { doc = (GuardedDocument)des.openDocument(); } JavaFXSource jfxs = JavaFXSource.forFileObject(handle.getFileObject()); jfxs.runWhenScanFinished(new Task<CompilationController>() { public void run(CompilationController cc) throws Exception { JavaFXTreePath path = handle.resolve(cc); TokenSequence<JFXTokenId> tokens = cc.getTreeUtilities().tokensFor(path.getLeaf()); tokens.moveStart(); while (tokens.moveNext()) { Token<JFXTokenId> token = tokens.token(); if (handle.getSimpleName().equals(token.text().toString())) { startPosition = token.offset(cc.getTokenHierarchy()); endPosition = startPosition + token.length(); break; } } } }, true); try { doc.readLock(); if (startPosition != -1) { int sta = Utilities.getRowFirstNonWhite(doc, startPosition); if (sta == -1) { sta = Utilities.getRowStart(doc, startPosition); } int en = Utilities.getRowLastNonWhite(doc, startPosition); if (en == -1) { en = Utilities.getRowEnd(doc, startPosition); } else { // Last nonwhite - left side of the last char, not inclusive en++; } displayText = SourceUtils.getHtml(doc.getText(sta, en - sta + 1)); bounds = new PositionBounds(des.createPositionRef(startPosition, Bias.Forward), des.createPositionRef(endPosition, Bias.Forward)); } else { System.err.println("*** Can not resolve: " + handle); throw new IOException(); } } catch (BadLocationException e) { throw new IOException(e.getLocalizedMessage()); } finally { doc.readUnlock(); } }
diff --git a/src/server/database/BatchDB.java b/src/server/database/BatchDB.java index 4942d1b..46ddc48 100644 --- a/src/server/database/BatchDB.java +++ b/src/server/database/BatchDB.java @@ -1,133 +1,133 @@ /** * */ package server.database; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import model.Batch; /** * @author Derek Carr * */ public class BatchDB { private Database db; /** * * @param db */ public BatchDB(Database db) { this.db = db; } public Batch getBatch(int id) { PreparedStatement stmt = null; ResultSet rs = null; Batch batch = null; try { String sql = "SELECT * FROM vm_batch WHERE id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while(rs.next()) { int bid = rs.getInt(1); int numJobs = rs.getInt(2); String email = rs.getString(3); double timeEst = rs.getDouble(4); double timeAct = rs.getDouble(5); boolean completed = rs.getBoolean(6); Timestamp createdDate = rs.getTimestamp(7); Timestamp modifiedDate = rs.getTimestamp(8); batch = new Batch(bid, numJobs, email, timeEst, timeAct, completed, createdDate, modifiedDate); } - sql = "SELECT sum(num_tests) FROM log_queue WHERE id = ?"; + sql = "SELECT sum(num_tests) FROM log_queue WHERE vm_batch_id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { int numberTests = rs.getInt(1); batch.setNumberTests(numberTests); } } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return batch; } public void setBatchCompleted(int batchId) { PreparedStatement stmt = null; try { String sql = "UPDATE vm_batch SET completed = 1 WHERE id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, batchId); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public boolean isBatchComplete(int batchId) { PreparedStatement stmt = null; ResultSet rs = null; boolean complete = true; try { String sql = "SELECT completed FROM vm_batch WHERE id = ?;"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, batchId); rs = stmt.executeQuery(); while (rs.next()) { if (!rs.getBoolean("completed")) { complete = false; } } } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return complete; } }
true
true
public Batch getBatch(int id) { PreparedStatement stmt = null; ResultSet rs = null; Batch batch = null; try { String sql = "SELECT * FROM vm_batch WHERE id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while(rs.next()) { int bid = rs.getInt(1); int numJobs = rs.getInt(2); String email = rs.getString(3); double timeEst = rs.getDouble(4); double timeAct = rs.getDouble(5); boolean completed = rs.getBoolean(6); Timestamp createdDate = rs.getTimestamp(7); Timestamp modifiedDate = rs.getTimestamp(8); batch = new Batch(bid, numJobs, email, timeEst, timeAct, completed, createdDate, modifiedDate); } sql = "SELECT sum(num_tests) FROM log_queue WHERE id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { int numberTests = rs.getInt(1); batch.setNumberTests(numberTests); } } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return batch; }
public Batch getBatch(int id) { PreparedStatement stmt = null; ResultSet rs = null; Batch batch = null; try { String sql = "SELECT * FROM vm_batch WHERE id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while(rs.next()) { int bid = rs.getInt(1); int numJobs = rs.getInt(2); String email = rs.getString(3); double timeEst = rs.getDouble(4); double timeAct = rs.getDouble(5); boolean completed = rs.getBoolean(6); Timestamp createdDate = rs.getTimestamp(7); Timestamp modifiedDate = rs.getTimestamp(8); batch = new Batch(bid, numJobs, email, timeEst, timeAct, completed, createdDate, modifiedDate); } sql = "SELECT sum(num_tests) FROM log_queue WHERE vm_batch_id = ?"; stmt = db.getConnection().prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { int numberTests = rs.getInt(1); batch.setNumberTests(numberTests); } } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return batch; }
diff --git a/src/main/java/ca/q0r/mchat/variables/VariableManager.java b/src/main/java/ca/q0r/mchat/variables/VariableManager.java index 27050aa..0f8ec4c 100644 --- a/src/main/java/ca/q0r/mchat/variables/VariableManager.java +++ b/src/main/java/ca/q0r/mchat/variables/VariableManager.java @@ -1,251 +1,251 @@ package ca.q0r.mchat.variables; import ca.q0r.mchat.api.API; import ca.q0r.mchat.types.IndicatorType; import ca.q0r.mchat.util.MessageUtil; import ca.q0r.mchat.variables.vars.*; import com.herocraftonline.heroes.Heroes; import com.palmergames.bukkit.towny.object.TownyUniverse; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import uk.org.whoami.geoip.GeoIPLookup; import uk.org.whoami.geoip.GeoIPTools; import java.lang.reflect.Method; import java.util.*; /** * Manager for Variables. */ public class VariableManager { private static Set<Var> varSet; // GeoIP private static GeoIPLookup geoip; private static Boolean geoipB; // Heroes private static Boolean heroesB; private static Heroes heroes; // Towny private static Boolean townyB; /** * Initializes Manager. */ public static void initialize() { varSet = new HashSet<Var>(); setupPlugins(); // Initialize GeoIP Vars if (geoipB) { GeoIpVars.addVars(geoip); } // Initialize Player Vars PlayerVars.addVars(); // Initialize Heroes Vars if (heroesB) { HeroesVars.addVars(heroes.getCharacterManager()); } // Initialize Towny Vars if (townyB) { try { TownyVars.addVars(TownyUniverse.getDataSource()); } catch (Exception ignored) {} } MessageVars.addVars(); } /** * Adds Var to VarSet. * @param var Variable processor. */ public static void addVar(Var var) { if (var != null) { varSet.add(var); } } /** * Adds Vars to VarSet. * @param vars Variable processor Array. */ public static void addVars(Var[] vars) { if (vars != null) { for (Var var : vars) { addVar(var); } } } /** * Variable Replacer. * @param format String to be replaced. * @param player Player being formatted against. * @param msg Message being relayed. * @param doColour Whether or not to colour replacement value. * @return String with Variables replaced. */ public static String replaceVars(String format, Player player, String msg, Boolean doColour) { NavigableMap<String, Object> fVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> nVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> lVarMap = new TreeMap<String, Object>(); for (Var var : varSet) { Method[] methods = var.getClass().getMethods(); for (Method method : methods) { ResolvePriority priority = ResolvePriority.NORMAL; IndicatorType type = IndicatorType.MISC_VAR; String[] keys = {}; String value = ""; if (method.isAnnotationPresent(Var.Keys.class)) { Var.Keys vKeys = method.getAnnotation(Var.Keys.class); keys = vKeys.keys(); if (msg != null && var instanceof MessageVars.MessageVar) { value = var.getValue(msg).toString(); } else { value = var.getValue(player).toString(); } } if (method.isAnnotationPresent(Var.Meta.class)) { Var.Meta vMeta = method.getAnnotation(Var.Meta.class); priority = vMeta.priority(); type = vMeta.type(); } switch(priority) { case FIRST: for (String key : keys) { fVarMap.put(type.getValue() + key, value); } break; case NORMAL: for (String key : keys) { nVarMap.put(type.getValue() + key, value); } break; case LAST: for (String key : keys) { lVarMap.put(type.getValue() + key, value); } break; default: for (String key : keys) { nVarMap.put(type + key, value); } break; } } } fVarMap = fVarMap.descendingMap(); nVarMap = nVarMap.descendingMap(); lVarMap = lVarMap.descendingMap(); format = replacer(format, fVarMap, doColour); format = replacer(format, nVarMap, doColour); - format = replacer(format, lVarMap, doColour); + format = replacer(format, lVarMap, false); return format; } /** * Custom Variable Replacer. * @param pName Player's Name. * @param format String to be replaced. * @return String with Custom Variables replaced. */ public static String replaceCustVars(String pName, String format) { if (!API.getVarMapQueue().isEmpty()) { API.getVarMap().putAll(API.getVarMapQueue()); API.getVarMapQueue().clear(); } Set<Map.Entry<String, Object>> entrySet = API.getVarMap().entrySet(); for (Map.Entry<String, Object> entry : entrySet) { String pKey = IndicatorType.CUS_VAR.getValue() + entry.getKey().replace(pName + "|", ""); String value = entry.getValue().toString(); if (format.contains(pKey)) { format = format.replace(pKey, MessageUtil.addColour(value)); } } for (Map.Entry<String, Object> entry : entrySet) { String gKey = IndicatorType.CUS_VAR.getValue() + entry.getKey().replace("%^global^%|", ""); String value = entry.getValue().toString(); if (format.contains(gKey)) { format = format.replace(gKey, MessageUtil.addColour(value)); } } return format; } private static String replacer(String format, Map<String, Object> map, Boolean doColour) { for (Map.Entry<String, Object> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue().toString(); if (doColour) { value = MessageUtil.addColour(value); } format = format.replace(key, value); } return format; } private static void setupPlugins() { PluginManager pm = Bukkit.getPluginManager(); // Setup GeoIPTools geoipB = setupPlugin("GeoIPTools"); if (geoipB) { geoip = ((GeoIPTools) pm.getPlugin("GeoIPTools")).getGeoIPLookup(); } // Setup Heroes heroesB = setupPlugin("Heroes"); if (heroesB) { heroes = (Heroes) pm.getPlugin("Heroes"); } townyB = setupPlugin("Towny"); } private static Boolean setupPlugin(String pluginName) { Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName); if (plugin != null && plugin.isEnabled()) { MessageUtil.logFormatted("<Plugin> " + plugin.getDescription().getName() + " v" + plugin.getDescription().getVersion() + " hooked!."); return true; } return false; } }
true
true
public static String replaceVars(String format, Player player, String msg, Boolean doColour) { NavigableMap<String, Object> fVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> nVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> lVarMap = new TreeMap<String, Object>(); for (Var var : varSet) { Method[] methods = var.getClass().getMethods(); for (Method method : methods) { ResolvePriority priority = ResolvePriority.NORMAL; IndicatorType type = IndicatorType.MISC_VAR; String[] keys = {}; String value = ""; if (method.isAnnotationPresent(Var.Keys.class)) { Var.Keys vKeys = method.getAnnotation(Var.Keys.class); keys = vKeys.keys(); if (msg != null && var instanceof MessageVars.MessageVar) { value = var.getValue(msg).toString(); } else { value = var.getValue(player).toString(); } } if (method.isAnnotationPresent(Var.Meta.class)) { Var.Meta vMeta = method.getAnnotation(Var.Meta.class); priority = vMeta.priority(); type = vMeta.type(); } switch(priority) { case FIRST: for (String key : keys) { fVarMap.put(type.getValue() + key, value); } break; case NORMAL: for (String key : keys) { nVarMap.put(type.getValue() + key, value); } break; case LAST: for (String key : keys) { lVarMap.put(type.getValue() + key, value); } break; default: for (String key : keys) { nVarMap.put(type + key, value); } break; } } } fVarMap = fVarMap.descendingMap(); nVarMap = nVarMap.descendingMap(); lVarMap = lVarMap.descendingMap(); format = replacer(format, fVarMap, doColour); format = replacer(format, nVarMap, doColour); format = replacer(format, lVarMap, doColour); return format; }
public static String replaceVars(String format, Player player, String msg, Boolean doColour) { NavigableMap<String, Object> fVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> nVarMap = new TreeMap<String, Object>(); NavigableMap<String, Object> lVarMap = new TreeMap<String, Object>(); for (Var var : varSet) { Method[] methods = var.getClass().getMethods(); for (Method method : methods) { ResolvePriority priority = ResolvePriority.NORMAL; IndicatorType type = IndicatorType.MISC_VAR; String[] keys = {}; String value = ""; if (method.isAnnotationPresent(Var.Keys.class)) { Var.Keys vKeys = method.getAnnotation(Var.Keys.class); keys = vKeys.keys(); if (msg != null && var instanceof MessageVars.MessageVar) { value = var.getValue(msg).toString(); } else { value = var.getValue(player).toString(); } } if (method.isAnnotationPresent(Var.Meta.class)) { Var.Meta vMeta = method.getAnnotation(Var.Meta.class); priority = vMeta.priority(); type = vMeta.type(); } switch(priority) { case FIRST: for (String key : keys) { fVarMap.put(type.getValue() + key, value); } break; case NORMAL: for (String key : keys) { nVarMap.put(type.getValue() + key, value); } break; case LAST: for (String key : keys) { lVarMap.put(type.getValue() + key, value); } break; default: for (String key : keys) { nVarMap.put(type + key, value); } break; } } } fVarMap = fVarMap.descendingMap(); nVarMap = nVarMap.descendingMap(); lVarMap = lVarMap.descendingMap(); format = replacer(format, fVarMap, doColour); format = replacer(format, nVarMap, doColour); format = replacer(format, lVarMap, false); return format; }
diff --git a/wicket-contrib-dojo/src/main/java/wicket/contrib/markup/html/form/validation/FXTooltipFeedbackPanel.java b/wicket-contrib-dojo/src/main/java/wicket/contrib/markup/html/form/validation/FXTooltipFeedbackPanel.java index 48a2095d5..3e39d6243 100644 --- a/wicket-contrib-dojo/src/main/java/wicket/contrib/markup/html/form/validation/FXTooltipFeedbackPanel.java +++ b/wicket-contrib-dojo/src/main/java/wicket/contrib/markup/html/form/validation/FXTooltipFeedbackPanel.java @@ -1,286 +1,286 @@ /* * $Id: FXTooltipFeedbackPanel.java 560 2006-01-25 07:47:44 -0800 (Wed, 25 Jan * 2006) marcovandehaar $ $Revision$ $Date: 2006-01-25 07:47:44 -0800 * (Wed, 25 Jan 2006) $ * * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package wicket.contrib.markup.html.form.validation; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import wicket.AttributeModifier; import wicket.MarkupContainer; import wicket.feedback.ComponentFeedbackMessageFilter; import wicket.feedback.FeedbackMessage; import wicket.feedback.FeedbackMessagesModel; import wicket.feedback.IFeedback; import wicket.feedback.IFeedbackMessageFilter; import wicket.markup.html.WebMarkupContainer; import wicket.markup.html.basic.Label; import wicket.markup.html.form.FormComponent; import wicket.markup.html.list.ListItem; import wicket.markup.html.list.ListView; import wicket.markup.html.panel.Panel; import wicket.model.IModel; import wicket.model.Model; /** * FeedbackPanel used in FXFeedbackTooltip Created as an external class in order * to let it define it's own UL and LI styles in FXTooltipFeedbackPanel.html. * * @author Marco van de Haar * @author Ruud Booltink */ public class FXTooltipFeedbackPanel extends Panel implements IFeedback { /** * List for messages. */ private final class MessageListView extends ListView<FeedbackMessage> { private static final long serialVersionUID = 1L; /** * @param parent * @param id * @see wicket.Component#Component(String) */ public MessageListView(MarkupContainer parent, final String id) { super(parent, id); setModel(newFeedbackMessagesModel()); } /** * @see wicket.markup.html.list.ListView#populateItem(wicket.markup.html.list.ListItem) */ protected void populateItem(final ListItem<FeedbackMessage> listItem) { final FeedbackMessage message = listItem.getModelObject(); final IModel replacementModel = new Model() { private static final long serialVersionUID = 1L; /** * Returns feedbackPanel + the message level, eg * 'feedbackPanelERROR'. This is used as the class of the li / * span elements. * * @see wicket.model.IModel#getObject() */ public Object getObject() { return getCSSClass(message); } }; - final Label label = new Label(listItem, "message", message.getMessage()); + final Label label = new Label(listItem, "message", message.getMessage().toString()); label.setEscapeModelStrings(getEscapeMessages()); final AttributeModifier levelModifier = new AttributeModifier("class", replacementModel); label.add(levelModifier); listItem.add(levelModifier); } } private static final long serialVersionUID = 1L; /** whether model messages should be HTML escaped. Default is true. */ private boolean escapeMessages = true; private ComponentFeedbackMessageFilter filter; /** Message view */ private final MessageListView messageListView; /** * @param parent * @param id * @param c * @see wicket.Component#Component(String) */ public FXTooltipFeedbackPanel(MarkupContainer parent, final String id, FormComponent c) { super(parent, id); WebMarkupContainer messagesContainer = new WebMarkupContainer(this, "feedbackul") { private static final long serialVersionUID = 1L; public boolean isVisible() { return anyMessage(); } }; filter = new ComponentFeedbackMessageFilter(c); this.messageListView = new MessageListView(messagesContainer, "messages"); messageListView.setVersioned(false); } /** * Gets whether model messages should be HTML escaped. Default is true. * * @return whether model messages should be HTML escaped */ public final boolean getEscapeMessages() { return escapeMessages; } /** * @see wicket.Component#isVersioned() */ public boolean isVersioned() { return false; // makes no sense to version the feedback panel } /** * Sets whether model messages should be HTML escaped. Default is true. * * @param escapeMessages * whether model messages should be HTML escaped */ public final void setEscapeMessages(boolean escapeMessages) { this.escapeMessages = escapeMessages; } /** * @param maxMessages * The maximum number of feedback messages that this feedback * panel should show at one time */ public final void setMaxMessages(int maxMessages) { this.messageListView.setViewSize(maxMessages); } /** * Sets the comparator used for sorting the messages. * * @param sortingComparator * comparator used for sorting the messages. */ public final void setSortingComparator(Comparator<FeedbackMessage> sortingComparator) { FeedbackMessagesModel feedbackMessagesModel = (FeedbackMessagesModel)messageListView .getModel(); feedbackMessagesModel.setSortingComparator(sortingComparator); } /** * @see wicket.feedback.IFeedback#updateFeedback() */ public void updateFeedback() { // Force model to load messageListView.getModelObject(); } /** * Search messages that this panel will render, and see if there is any * message of level ERROR or up. This is a convenience method; same as * calling 'anyMessage(FeedbackMessage.ERROR)'. * * @return whether there is any message for this panel of level ERROR or up */ protected final boolean anyErrorMessage() { return anyMessage(FeedbackMessage.ERROR); } /** * Search messages that this panel will render, and see if there is any * message. * * @return whether there is any message for this panel */ protected final boolean anyMessage() { return anyMessage(FeedbackMessage.UNDEFINED); } /** * Search messages that this panel will render, and see if there is any * message of the given level. * * @param level * the level, see FeedbackMessage * @return whether there is any message for this panel of the given level */ protected final boolean anyMessage(int level) { List msgs = getCurrentMessages(); for (Iterator i = msgs.iterator(); i.hasNext();) { FeedbackMessage msg = (FeedbackMessage)i.next(); if (msg.isLevel(level)) { return true; } } return false; } /** * Gets the css class for the given message. * * @param message * the message * @return the css class; by default, this returns feedbackPanel + the * message level, eg 'feedbackPanelERROR', but you can override this * method to provide your own */ protected String getCSSClass(FeedbackMessage message) { return "feedbackTooltipERROR"; } /** * Gets the currently collected messages for this panel. * * @return the currently collected messages for this panel, possibly empty */ protected final List<FeedbackMessage> getCurrentMessages() { final List<FeedbackMessage> messages = messageListView.getModelObject(); return Collections.unmodifiableList(messages); } /** * @return Let subclass specify some other filter */ protected IFeedbackMessageFilter getFeedbackMessageFilter() { return filter; } /** * Gets a new instance of FeedbackMessagesModel to use. * * @return instance of FeedbackMessagesModel to use */ protected FeedbackMessagesModel newFeedbackMessagesModel() { return new FeedbackMessagesModel(getPage(), getFeedbackMessageFilter()); } }
true
true
protected void populateItem(final ListItem<FeedbackMessage> listItem) { final FeedbackMessage message = listItem.getModelObject(); final IModel replacementModel = new Model() { private static final long serialVersionUID = 1L; /** * Returns feedbackPanel + the message level, eg * 'feedbackPanelERROR'. This is used as the class of the li / * span elements. * * @see wicket.model.IModel#getObject() */ public Object getObject() { return getCSSClass(message); } }; final Label label = new Label(listItem, "message", message.getMessage()); label.setEscapeModelStrings(getEscapeMessages()); final AttributeModifier levelModifier = new AttributeModifier("class", replacementModel); label.add(levelModifier); listItem.add(levelModifier); }
protected void populateItem(final ListItem<FeedbackMessage> listItem) { final FeedbackMessage message = listItem.getModelObject(); final IModel replacementModel = new Model() { private static final long serialVersionUID = 1L; /** * Returns feedbackPanel + the message level, eg * 'feedbackPanelERROR'. This is used as the class of the li / * span elements. * * @see wicket.model.IModel#getObject() */ public Object getObject() { return getCSSClass(message); } }; final Label label = new Label(listItem, "message", message.getMessage().toString()); label.setEscapeModelStrings(getEscapeMessages()); final AttributeModifier levelModifier = new AttributeModifier("class", replacementModel); label.add(levelModifier); listItem.add(levelModifier); }
diff --git a/Server/src/main/java/jk_5/nailed/server/command/CommandSudo.java b/Server/src/main/java/jk_5/nailed/server/command/CommandSudo.java index 8fa6f3e..b60a985 100644 --- a/Server/src/main/java/jk_5/nailed/server/command/CommandSudo.java +++ b/Server/src/main/java/jk_5/nailed/server/command/CommandSudo.java @@ -1,44 +1,44 @@ package jk_5.nailed.server.command; import com.google.common.base.Joiner; import cpw.mods.fml.common.FMLCommonHandler; import jk_5.nailed.map.Map; import jk_5.nailed.players.Player; import jk_5.nailed.players.PlayerRegistry; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import java.util.Arrays; import java.util.List; /** * No description given * * @author jk-5 */ public class CommandSudo extends NailedCommand { @Override public String getCommandName(){ return "sudo"; } @Override public void processCommandWithMap(ICommandSender sender, Map map, String[] args){ + Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]); args[0] = null; String cmd = Joiner.on(" ").skipNulls().join(args); - Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]); if (player != null){ FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager().executeCommand(player.getEntity(), cmd); }else{ throw new CommandException("Unknown player"); } } @Override public List addTabCompletionOptions(ICommandSender iCommandSender, String[] strings){ if(strings.length != 1) return Arrays.asList(); return getListOfStringsMatchingLastWord(strings, MinecraftServer.getServer().getAllUsernames()); } }
false
true
public void processCommandWithMap(ICommandSender sender, Map map, String[] args){ args[0] = null; String cmd = Joiner.on(" ").skipNulls().join(args); Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]); if (player != null){ FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager().executeCommand(player.getEntity(), cmd); }else{ throw new CommandException("Unknown player"); } }
public void processCommandWithMap(ICommandSender sender, Map map, String[] args){ Player player = PlayerRegistry.instance().getPlayerByUsername(args[0]); args[0] = null; String cmd = Joiner.on(" ").skipNulls().join(args); if (player != null){ FMLCommonHandler.instance().getMinecraftServerInstance().getCommandManager().executeCommand(player.getEntity(), cmd); }else{ throw new CommandException("Unknown player"); } }
diff --git a/src/org/ruhlendavis/mc/communitybridge/WebApplication.java b/src/org/ruhlendavis/mc/communitybridge/WebApplication.java index 102563e..64ddec9 100644 --- a/src/org/ruhlendavis/mc/communitybridge/WebApplication.java +++ b/src/org/ruhlendavis/mc/communitybridge/WebApplication.java @@ -1,1322 +1,1322 @@ package org.ruhlendavis.mc.communitybridge; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.netmanagers.api.SQL; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.ruhlendavis.mc.utility.Log; import org.ruhlendavis.utility.StringUtilities; /** * Class representing the interface to the web application. * * @author Feaelin (Iain E. Davis) <[email protected]> */ public class WebApplication { private CommunityBridge plugin; private Configuration config; private Log log; private SQL sql; private int maxPlayers; private Map<String, String> playerUserIDs = new HashMap<String, String>(); private List<Player> synchronizationLocks = new ArrayList<Player>(); public WebApplication(CommunityBridge plugin, Configuration config, Log log, SQL sql) { this.config = config; this.plugin = plugin; this.log = log; setSQL(sql); this.maxPlayers = Bukkit.getMaxPlayers(); } /** * Returns a given player's web application user ID. * * @param String containing the player's name. * @return String containing the player's web application user ID. */ public String getUserID(String playerName) { if (!playerUserIDs.containsKey(playerName)) { loadUserIDfromDatabase(playerName); } return playerUserIDs.get(playerName); } /** * Returns true if the user's avatar column contains data. * * @param String The player's name. * @return boolean True if the user has an avatar. */ public boolean playerHasAvatar(String playerName) { final String errorBase = "Error during WebApplication.playerHasAvatar(): "; String query; query = "SELECT `" + config.requireAvatarTableName + "`.`" + config.requireAvatarAvatarColumn + "` " + "FROM `" + config.requireAvatarTableName + "` " + "WHERE `" + config.requireAvatarUserIDColumn + "` = '" + getUserID(playerName) + "'"; try { String avatar = null; ResultSet result = sql.sqlQuery(query); if (result.next()) { avatar = result.getString(config.requireAvatarAvatarColumn); } if (avatar == null || avatar.isEmpty()) { return false; } else { return true; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return false; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return false; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return false; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return false; } } /** * Fetches the user's post count from the web application. * * @param String The player's name. * @return int Number of posts. */ public int getUserPostCount(String playerName) { final String errorBase = "Error during WebApplication.getUserPostCount(): "; String query; query = "SELECT `" + config.requirePostsTableName + "`.`" + config.requirePostsPostCountColumn + "` " + "FROM `" + config.requirePostsTableName + "` " + "WHERE `" + config.requirePostsUserIDColumn + "` = '" + getUserID(playerName) + "'"; try { ResultSet result = sql.sqlQuery(query); if (result.next()) { return result.getInt(config.requirePostsPostCountColumn); } else { return 0; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return 0; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return 0; } } /** * Retrieves a player's primary group ID from the web application database. * * @param String player name to retrieve. * @return String containing the group ID or null if there was an error or it doesn't exist. */ public String getUserPrimaryGroupID(String playerName) { if (!config.webappPrimaryGroupEnabled) { return ""; } final String errorBase = "Error during WebApplication.getUserPrimaryGroupID(): "; String query; if (config.webappPrimaryGroupUsesKey) { query = "SELECT `" + config.webappPrimaryGroupGroupIDColumn + "` " + "FROM `" + config.webappPrimaryGroupTable + "` " + "WHERE `" + config.webappPrimaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "' " + "AND `" + config.webappPrimaryGroupKeyColumn + "` = '" + config.webappPrimaryGroupKeyName + "' "; } else { query = "SELECT `" + config.webappPrimaryGroupGroupIDColumn + "` " + "FROM `" + config.webappPrimaryGroupTable + "` " + "WHERE `" + config.webappPrimaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "'"; } try { ResultSet result = sql.sqlQuery(query); if (result.next()) { return result.getString(config.webappPrimaryGroupGroupIDColumn); } else { return ""; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return ""; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return ""; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return ""; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return ""; } } public List<String> getUserGroupIDs(String playerName) { if (!config.webappSecondaryGroupEnabled) { return null; } if (config.webappSecondaryGroupStorageMethod.startsWith("sin")) { return getUserGroupIDsSingleColumn(playerName); } else if (config.webappSecondaryGroupStorageMethod.startsWith("jun")) { return getUserGroupIDsJunction(playerName); } else if (config.webappSecondaryGroupStorageMethod.startsWith("key")) { return getUserGroupIDsKeyValue(playerName); } else if (config.webappSecondaryGroupStorageMethod.startsWith("mul")) { return getUserGroupIDsMultipleKeyValue(playerName); } log.severe("Invalid storage method for secondary groups."); return null; } private List<String> getUserGroupIDsSingleColumn(String playerName) { final String errorBase = "Error during WebApplication.getUserGroupIDsSingleColumn(): "; String query; query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "' "; try { ResultSet result = sql.sqlQuery(query); if (result.next()) { return new ArrayList<String>(Arrays.asList(result.getString(config.webappSecondaryGroupGroupIDColumn).split(config.webappSecondaryGroupGroupIDDelimiter))); } else { return null; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return null; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return null; } } private List<String> getUserGroupIDsKeyValue(String playerName) { final String errorBase = "Error during WebApplication.getUserGroupIDsKeyValue(): "; String query; query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "' " + "AND `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' "; try { ResultSet result = sql.sqlQuery(query); if (result.next()) { return new ArrayList<String>(Arrays.asList(result.getString(config.webappSecondaryGroupGroupIDColumn).split(config.webappSecondaryGroupGroupIDDelimiter))); } else { return null; } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return null; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return null; } } private List<String> getUserGroupIDsJunction(String playerName) { final String errorBase = "Error during WebApplication.getUserGroupIDsJunction(): "; String query; query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "' "; try { ResultSet result = sql.sqlQuery(query); List<String> groupIDs = new ArrayList<String>(); while (result.next()) { groupIDs.add(result.getString(config.webappSecondaryGroupGroupIDColumn)); } return groupIDs; } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return null; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return null; } } private List<String> getUserGroupIDsMultipleKeyValue(String playerName) { final String errorBase = "Error during WebApplication.getUserGroupIDsKeyValue(): "; String query; query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + getUserID(playerName) + "' " + "AND `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' "; try { ResultSet result = sql.sqlQuery(query); List<String> groupIDs = new ArrayList<String>(); while (result.next()) { groupIDs.add(result.getString(config.webappSecondaryGroupGroupIDColumn)); } return groupIDs; } catch (SQLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); return null; } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); return null; } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); return null; } } /** * Returns true if the player is registered on the web application. * @param String The name of the player. * @return boolean True if the player is registered. */ public boolean isPlayerRegistered(String playerName) { return !(getUserID(playerName) == null || getUserID(playerName).isEmpty()); } /** * Retrieves user IDs for all connected players, required after a cache * cleanup and after cb reload. */ public synchronized void loadOnlineUserIDsFromDatabase() { Player [] players = Bukkit.getOnlinePlayers(); for (Player player : players) { loadUserIDfromDatabase(player.getName()); } } /** * Performs the database query that should be done when a player connects. * * @param String containing the player's name. */ public synchronized void loadUserIDfromDatabase(String playerName) { if (playerUserIDs.size() >= (maxPlayers * 4)) { playerUserIDs.clear(); loadOnlineUserIDsFromDatabase(); } final String errorBase = "Error during WebApplication.onPreLogin(): "; String query = "SELECT `" + config.linkingTableName + "`.`" + config.linkingUserIDColumn + "` " + "FROM `" + config.linkingTableName + "` "; if (config.linkingUsesKey) { query = query + "WHERE `" + config.linkingKeyColumn + "` = '" + config.linkingKeyName + "' " + "AND `" + config.linkingValueColumn + "` = '" + playerName + "' "; } else { query = query + "WHERE LOWER(`" + config.linkingPlayerNameColumn + "`) = LOWER('" + playerName + "') "; } query = query + "ORDER BY `" + config.linkingUserIDColumn + "` DESC"; try { String userID = null; ResultSet result = sql.sqlQuery(query); if (result.next()) { userID = result.getString(config.linkingUserIDColumn); } if (userID == null) { log.finest("User ID for " + playerName + " not found."); } else { log.finest("User ID '" + userID + "' associated with " + playerName + "."); playerUserIDs.put(playerName, userID); } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } // loadUserIDfromDatabase() /** * Performs operations when a player joins * * @param String The player who joined. */ public void onJoin(final Player player) { runSynchronizePlayer(player, true); } /** * Performs operations when a player quits. * * @param String containing the player's name. */ public void onQuit(Player player) { runSynchronizePlayer(player, false); } /** * If statistics is enabled, this method sets up an update statistics task * for the given player. * * @param String The player's name. */ public void runSynchronizePlayer(final Player player, final boolean online) { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { synchronizePlayer(player, online); } }); } public void runSynchronizeAll() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { synchronizeAll(); } }); } public void synchronizeAll() { Player[] onlinePlayers = Bukkit.getOnlinePlayers(); for (Player player : onlinePlayers) { synchronizePlayer(player, true); } } private void synchronizePlayer(Player player, boolean online) { if (!synchronizationLocks.contains(player)) { synchronizationLocks.add(player); if (config.groupSynchronizationActive) { synchronizeGroups(player); } if (config.statisticsEnabled) { updateStatistics(player, online); } synchronizationLocks.remove(player); } } /** * Sets the SQL object. Typically used during a reload. * * @param SQL SQL object to set. */ public final void setSQL(SQL sql) { this.sql = sql; } private void setPrimaryGroup(String userID, String groupID) { String errorBase = "Error during setPrimaryGroup(): "; try { if (config.webappPrimaryGroupUsesKey) { String query = "UPDATE `" + config.webappPrimaryGroupTable + "` " + "SET `" + config.webappPrimaryGroupGroupIDColumn + "` = '" + groupID + "' " + "WHERE `" + config.webappPrimaryGroupKeyColumn + "` = '" + config.webappPrimaryGroupKeyName + "' " + "AND `" + config.webappPrimaryGroupUserIDColumn + "` = '" + userID + "'"; sql.updateQuery(query); } else { String query = "UPDATE `" + config.webappPrimaryGroupTable + "` " + "SET `" + config.webappPrimaryGroupGroupIDColumn + "` = '" + groupID + "' " + "WHERE `" + config.webappPrimaryGroupUserIDColumn + "` = '" + userID + "' "; sql.updateQuery(query); } } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } private void synchronizeGroups(Player player) { String playerName = player.getName(); String direction = config.simpleSynchronizationDirection; String userID = getUserID(playerName); if (userID.equalsIgnoreCase(config.simpleSynchronizationSuperUserID)) { direction = "web"; } File playerFolder = new File(plugin.getDataFolder(), "Players"); // 1. Retrieve previous group state for forum groups and permissions groups. PlayerGroupState previousState = new PlayerGroupState(playerName, playerFolder); previousState.load(); // 2. Capture current group state PlayerGroupState currentState = new PlayerGroupState(playerName, playerFolder); currentState.generate(); // 3. Synchronize primary group state if (config.webappPrimaryGroupEnabled) { if (direction.startsWith("two") || direction.startsWith("web") && !previousState.webappPrimaryGroupID.equals(currentState.webappPrimaryGroupID)) { String formerGroupName = config.getGroupNameByGroupID(previousState.webappPrimaryGroupID); String newGroupName = config.getGroupNameByGroupID(currentState.webappPrimaryGroupID); if (newGroupName == null) { log.warning("Not changing permissions group due to permissions system group name lookup failure for web application group ID: " + currentState.webappPrimaryGroupID + ". Player '" + playerName + "' primary group state unchanged."); currentState.webappPrimaryGroupID = previousState.webappPrimaryGroupID; } else { maybeNotifyPlayerOfPrimaryGroupChange(newGroupName, player); if (CommunityBridge.permissionHandler.supportsPrimaryGroups()) { CommunityBridge.permissionHandler.setPrimaryGroup(playerName, newGroupName, formerGroupName); log.fine("Moved player '" + playerName + "' to permissions group '" + newGroupName + "'."); } else { CommunityBridge.permissionHandler.addToGroup(playerName, newGroupName); log.fine("Added pseudo-primary group '" + newGroupName + "' to player '" + playerName + "' list of permissions groups."); } } } if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && (direction.startsWith("two") || direction.startsWith("min")) && !previousState.permissionsSystemPrimaryGroupName.equals(currentState.permissionsSystemPrimaryGroupName)) { String groupID = config.getWebappGroupIDbyGroupName(currentState.permissionsSystemPrimaryGroupName); if (groupID == null) { log.warning("Not changing web application group due to web application group ID lookup failure for: " + currentState.permissionsSystemPrimaryGroupName + ". Player '" + playerName + "' primary group state unchanged."); currentState.permissionsSystemPrimaryGroupName = previousState.permissionsSystemPrimaryGroupName; } else { setPrimaryGroup(userID, groupID); log.fine("Moved player '" + playerName + "' to web application group ID '" + groupID + "'."); } } } // 4. Synchronize secondary group state if (config.webappSecondaryGroupEnabled) { - if (direction.startsWith("two") || direction.startsWith("web")) + if (direction.startsWith("two") || direction.startsWith("min")) { for (String groupName : previousState.permissionsSystemGroupNames) { if (!currentState.permissionsSystemGroupNames.contains(groupName) && !config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { removeGroup(userID, groupName); } } for (Iterator<String> iterator = currentState.permissionsSystemGroupNames.iterator(); iterator.hasNext();) { String groupName = iterator.next(); if (!previousState.permissionsSystemGroupNames.contains(groupName)) { String groupID = config.getWebappGroupIDbyGroupName(groupName); // Since the group is not in the mapping, we'll NOT record it as // part of the current state. That way, if the group is added to // the mapping later, we'll see it as a 'new' group and syncrhonize. if (groupID == null) { iterator.remove(); } else if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { this.setPrimaryGroup(userID, groupID); } else if (!currentState.webappPrimaryGroupID.equals(groupID) && !currentState.webappGroupIDs.contains(groupID)) { addGroup(userID, groupID, currentState.webappGroupIDs.size()); } } } } if (direction.startsWith("two") || direction.startsWith("web")) { for(String groupID : previousState.webappGroupIDs) { if (!currentState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); CommunityBridge.permissionHandler.removeFromGroup(playerName, groupName); } } for (Iterator<String> iterator = currentState.webappGroupIDs.iterator(); iterator.hasNext();) { String groupID = iterator.next(); if (!previousState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); // Since this group is not in the mapping, we shouldn't record it // This way, if the group is later added, it will be 'new' to us // and we will syncrhonize. if (groupName == null) { iterator.remove(); } else if (!currentState.permissionsSystemPrimaryGroupName.equals(groupName) && !currentState.permissionsSystemGroupNames.contains(groupName)) { CommunityBridge.permissionHandler.addToGroup(playerName, groupName); } // Check for null/primaryalreadyset/secondaryalreadyset } // if previousState contains group ID } // for each group ID in currentState } // Synchronization direction check. } // if SecondaryWebapp enabled. // 5. Save newly created state try { currentState.save(); } catch (IOException error) { log.severe("Error when saving group state for player " + playerName + ": " + error.getMessage()); } } /** * Handles adding a group to the user's group list on the web application. * * @param String Name from permissions system of group added. */ private void addGroup(String userID, String groupID, int currentGroupCount) { String errorBase = "Error during addGroup(): "; try { if (config.webappSecondaryGroupStorageMethod.startsWith("sin")) { if (currentGroupCount > 0) { groupID = config.webappSecondaryGroupGroupIDDelimiter + groupID; } String query = "UPDATE `" + config.webappSecondaryGroupTable + "` " + "SET `" + config.webappSecondaryGroupGroupIDColumn + "` = CONCAT(`" + config.webappSecondaryGroupGroupIDColumn + "`, '" + groupID + "') " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'"; sql.updateQuery(query); } else if (config.webappSecondaryGroupStorageMethod.startsWith("key")) { if (currentGroupCount > 0) { groupID = config.webappSecondaryGroupGroupIDDelimiter + groupID; } String query = "UPDATE `" + config.webappSecondaryGroupTable + "` " + "SET `" + config.webappSecondaryGroupGroupIDColumn + "` = CONCAT(`" + config.webappSecondaryGroupGroupIDColumn + "`, '" + groupID + "') " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' " + "AND `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' "; sql.updateQuery(query); } else if (config.webappSecondaryGroupStorageMethod.startsWith("jun")) { String query = "INSERT INTO `" + config.webappSecondaryGroupTable + "` " + "(`" + config.webappSecondaryGroupUserIDColumn + "`, `" + config.webappSecondaryGroupGroupIDColumn + "`) " + "VALUES ('" + userID + "', '" + groupID +"')"; sql.insertQuery(query); } else if (config.webappSecondaryGroupStorageMethod.startsWith("mul")) { String query = "INSERT INTO `" + config.webappSecondaryGroupTable + "` " + "(`" + config.webappSecondaryGroupUserIDColumn + "`, `" + config.webappPrimaryGroupKeyColumn + "`, `" + config.webappSecondaryGroupGroupIDColumn + "`) " + "VALUES ('" + userID + "', '" + config.webappSecondaryGroupKeyName + "', '" + groupID + "')"; sql.insertQuery(query); } } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } /** * Handles removing a group from the user's group list on the web application. * * @param String Name from permissions system of group to remove. */ private void removeGroup(String userID, String groupName) { String groupID = config.getWebappGroupIDbyGroupName(groupName); String errorBase = "Error during addGroup(): "; try { if (config.webappSecondaryGroupStorageMethod.startsWith("sin")) { String groupIDs; String query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'"; ResultSet result = sql.sqlQuery(query); if (result.next()) { groupIDs = result.getString(config.webappSecondaryGroupGroupIDColumn); List<String> groupIDsAsList = new ArrayList<String>(Arrays.asList(groupIDs.split(config.webappSecondaryGroupGroupIDDelimiter))); groupIDsAsList.remove(groupID); groupIDs = StringUtilities.joinStrings(groupIDsAsList, config.webappSecondaryGroupGroupIDDelimiter); query = "UPDATE `" + config.webappSecondaryGroupTable + "` " + "SET `" + config.webappSecondaryGroupGroupIDColumn + "` = '" + groupIDs + "' " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "'"; sql.updateQuery(query); } } else if (config.webappSecondaryGroupStorageMethod.startsWith("key")) { String groupIDs; String query = "SELECT `" + config.webappSecondaryGroupGroupIDColumn + "` " + "FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' " + "AND `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' "; ResultSet result = sql.sqlQuery(query); if (result.next()) { groupIDs = result.getString(config.webappSecondaryGroupGroupIDColumn); List<String> groupIDsAsList = new ArrayList<String>(Arrays.asList(groupIDs.split(config.webappSecondaryGroupGroupIDDelimiter))); groupIDsAsList.remove(groupID); groupIDs = StringUtilities.joinStrings(groupIDsAsList, config.webappSecondaryGroupGroupIDDelimiter); query = "UPDATE `" + config.webappSecondaryGroupTable + "` " + " SET `" + config.webappSecondaryGroupGroupIDColumn + "` = '" + groupIDs + "' " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' " + "AND `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' "; sql.updateQuery(query); } } else if (config.webappSecondaryGroupStorageMethod.startsWith("jun")) { String query = "DELETE FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupUserIDColumn + "` = '" + userID + "' " + "AND `" + config.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' "; sql.deleteQuery(query); } else if (config.webappSecondaryGroupStorageMethod.startsWith("mul")) { String query = "DELETE FROM `" + config.webappSecondaryGroupTable + "` " + "WHERE `" + config.webappSecondaryGroupKeyColumn + "` = '" + config.webappSecondaryGroupKeyName + "' " + "AND `" + config.webappSecondaryGroupGroupIDColumn + "` = '" + groupID + "' "; sql.deleteQuery(query); } } catch (SQLException error) { log.severe(errorBase + error.getMessage()); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } /** * Update the player's statistical information on the forum. * * @param String Name of player to update * @param boolean Set to true if the player is currently online */ private void updateStatistics(Player player, boolean online) { String query; ResultSet result; String playerName = player.getName(); String userID = getUserID(playerName); int previousLastOnline = 0; int previousGameTime = 0; // If gametime is enabled, it depends on lastonline. Also, we need to // retrieve previously recorded lastonline time and the previously // recorded gametime to compute the new gametime. if (config.gametimeEnabled) { if (config.statisticsUsesKey) { query = "SELECT `" + config.statisticsKeyColumn + "`, `" + config.statisticsValueColumn + "` " + "FROM `" + config.statisticsTableName + "` " + "WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); while (result.next()) { String key = result.getString(config.statisticsKeyColumn); if (key.equalsIgnoreCase(config.lastonlineColumnOrKey)) { previousLastOnline = result.getInt(config.statisticsValueColumn); } else if (key.equalsIgnoreCase(config.gametimeColumnOrKey)) { previousGameTime = result.getInt(config.statisticsValueColumn); } } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } else { query = "SELECT `" + config.lastonlineColumnOrKey + "`, `" + config.gametimeColumnOrKey + "`" + " FROM `" + config.statisticsTableName + "`" + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; try { result = sql.sqlQuery(query); if (result.next()) { previousLastOnline = result.getInt(config.lastonlineColumnOrKey); previousGameTime = result.getInt(config.gametimeColumnOrKey); } } catch (SQLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (MalformedURLException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (InstantiationException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } catch (IllegalAccessException error) { log.severe("Error in UpdateStatistics() during retrieval: " + error.getMessage()); } } } SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss a"); String onlineStatus; if (online) { onlineStatus = config.onlineStatusValueOnline; } else { onlineStatus = config.onlineStatusValueOffline; } // last online int lastonlineTime = (int) (System.currentTimeMillis() / 1000L); String lastonlineTimeFormatted = dateFormat.format(new Date()); // game time (time played) int gametime = 0; if (previousLastOnline > 0) { gametime = previousGameTime + lastonlineTime - previousLastOnline; } String gametimeFormatted = StringUtilities.timeElapsedtoString (gametime); int level = player.getLevel(); int totalxp = player.getTotalExperience(); float currentxp = player.getExp(); String currentxpFormatted = ((int)(currentxp * 100)) + "%"; int health = player.getHealth(); int lifeticks = player.getTicksLived(); String lifeticksFormatted = StringUtilities.timeElapsedtoString((int)(lifeticks / 20)); double wallet = 0.0; if (config.walletEnabled) { wallet = CommunityBridge.economy.getBalance(playerName); } if (config.statisticsUsesKey) { updateStatisticsKeyStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } else { updateStatisticsKeylessStyle(userID, onlineStatus, lastonlineTime, lastonlineTimeFormatted, gametime, gametimeFormatted, level, totalxp, currentxp, currentxpFormatted, health, lifeticks, lifeticksFormatted, wallet); } } /** * Called by updateStatistics() to update a statistics table that uses Key-Value Pairs. * * @param String Player's forum user ID. * @param String Set to the appropriate value representing player's online status. * @param int systime value for the last time the player was last online * @param String A formatted version of the systime value of when the player was last online. * @param int Amount of time the player has played in seconds. * @param String Amount of time the player has played formatted nicely. * @param int Level of the player * @param int Total amount of XP the player currently has. * @param float Amount of progress the player has towards the next level as a percentage. * @param String Readable version of the percentage the player has towards the next level. * @param int Player's current health level. * @param int Amount of time played since last death, in ticks. * @param String Formatted amount of time played since last death. * @param double Current balance of the player. */ private void updateStatisticsKeyStyle(String userID, String onlineStatus, int lastonlineTime, String lastonlineFormattedTime, int gameTime, String gameTimeFormatted, int level, int totalxp, float currentxp, String currentxpFormatted, int health, int lifeticks, String lifeticksFormatted, double wallet) { List<String> fields = new ArrayList<String>(); String query = "UPDATE `" + config.statisticsTableName + "` " + "SET "; /* To collapse multiple MySQL queries into one query, we're using the * MySQL CASE operator. Recommended reading: * http://www.karlrixon.co.uk/writing/update-multiple-rows-with-different-values-and-a-single-sql-query/ * Prototype: * UPDATE tablename * SET valueColumn = CASE keycolumn * WHEN keyname THEN keyvalue * WHEN keyname THEN keyvalue * END * WHERE useridcolumn = userid; */ query = query + "`" + config.statisticsValueColumn + "` = CASE " + "`" + config.statisticsKeyColumn + "` "; if (config.onlineStatusEnabled) { fields.add("WHEN '" + config.onlineStatusColumnOrKey + "' THEN '" + onlineStatus + "' "); } if (config.lastonlineEnabled) { fields.add("WHEN '" + config.lastonlineColumnOrKey + "' THEN '" + lastonlineTime + "' "); if (!config.lastonlineFormattedColumnOrKey.isEmpty()) { fields.add("WHEN '" + config.lastonlineFormattedColumnOrKey + "' THEN '" + lastonlineFormattedTime + "' "); } } // Gametime actually relies on the prior lastonlineTime... if (config.gametimeEnabled && config.lastonlineEnabled) { fields.add("WHEN '" + config.gametimeColumnOrKey + "' THEN '" + gameTime + "' "); if (!config.gametimeFormattedColumnOrKey.isEmpty()) { fields.add("WHEN '" + config.gametimeFormattedColumnOrKey + "' THEN '" + gameTimeFormatted + "' "); } } if (config.levelEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + level + "' "); } if (config.totalxpEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + totalxp + "' "); } if (config.currentxpEnabled) { fields.add("WHEN '" + config.levelColumnOrKey + "' THEN '" + currentxp + "' "); if (!config.currentxpFormattedColumnOrKey.isEmpty()) { fields.add("WHEN '" + config.currentxpFormattedColumnOrKey + "' THEN '" + currentxpFormatted + "' "); } } if (config.healthEnabled) { fields.add("WHEN '" + config.healthColumnOrKey + "' THEN '" + health + "' "); } if (config.lifeticksEnabled) { fields.add("WHEN '" + config.lifeticksColumnOrKey + "' THEN '" + lifeticks + "' "); if (!config.lifeticksFormattedColumnOrKey.isEmpty()) { fields.add("WHEN '" + config.lifeticksFormattedColumnOrKey + "' THEN '" + lifeticksFormatted + "' "); } } if (config.walletEnabled) { fields.add("WHEN '" + config.walletColumnOrKey + "' THEN '" + wallet + "' "); } query = query + StringUtilities.joinStrings(fields, " "); query = query + "END"; query = query + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; String errorBase = "Error during updateStatisticsKeyStyle(): "; try { sql.updateQuery(query); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } /** * Called by updateStatistics when updating a table that columns (instead of keyvalue pairs). * * @param String Player's forum user ID. * @param String Set to the appropriate value representing player's online status. * @param int systime value for the last time the player was last online * @param String A formatted version of the systime value of when the player was last online. * @param int Amount of time the player has played in seconds. * @param String Amount of time the player has played formatted nicely. * @param int Level of the player * @param int Total amount of XP the player currently has. * @param float Amount of progress the player has towards the next level as a percentage. * @param String Readable version of the percentage the player has towards the next level. * @param int Player's current health level. * @param int Amount of time played since last death, in ticks. * @param String Formatted amount of time played since last death. * @param double Current balance of the player. */ private void updateStatisticsKeylessStyle(String userID, String onlineStatus, int lastonlineTime, String lastonlineTimeFormatted, int gametime, String gametimeFormatted, int level, int totalxp, float currentxp, String currentxpFormatted, int health, int lifeticks, String lifeticksFormatted, double wallet) { String query; List<String> fields = new ArrayList<String>(); query = "UPDATE `" + config.statisticsTableName + "` " + "SET "; if (config.onlineStatusEnabled) { fields.add("`" + config.onlineStatusColumnOrKey + "` = '" + onlineStatus + "'"); } if (config.lastonlineEnabled) { fields.add("`" + config.lastonlineColumnOrKey + "` = '" + lastonlineTime + "'"); if (!config.lastonlineFormattedColumnOrKey.isEmpty()) { fields.add("`" + config.lastonlineFormattedColumnOrKey + "` = '" + lastonlineTimeFormatted + "'"); } } if (config.gametimeEnabled) { fields.add("`" + config.gametimeColumnOrKey + "` = '" + gametime + "'"); if (!config.gametimeFormattedColumnOrKey.isEmpty()) { fields.add("`" + config.gametimeFormattedColumnOrKey + "` = '" + gametimeFormatted + "'"); } } if (config.levelEnabled) { fields.add("`" + config.levelColumnOrKey + "` = '" + level + "'"); } if (config.totalxpEnabled) { fields.add("`" + config.totalxpColumnOrKey + "` = '" + totalxp + "'"); } if (config.currentxpEnabled) { fields.add("`" + config.currentxpColumnOrKey + "` = '" + currentxp + "'"); if (!config.currentxpFormattedColumnOrKey.isEmpty()) { fields.add("`" + config.currentxpFormattedColumnOrKey + "` = '" + currentxpFormatted + "'"); } } if (config.healthEnabled) { fields.add("`" + config.healthColumnOrKey + "` = '" + health + "'"); } if (config.lifeticksEnabled) { fields.add("`" + config.lifeticksColumnOrKey + "` = '" + lifeticks + "'"); if (!config.lifeticksFormattedColumnOrKey.isEmpty()) { fields.add("`" + config.lifeticksFormattedColumnOrKey + "` = '" + lifeticksFormatted + "'"); } } if (config.walletEnabled) { fields.add("`" + config.walletColumnOrKey + "` = '" + wallet + "'"); } query = query + StringUtilities.joinStrings(fields, ", ") + " WHERE `" + config.statisticsUserIDColumn + "` = '" + userID + "'"; String errorBase = "Error during updateStatisticsKeylessStyle(): "; try { sql.updateQuery(query); } catch (MalformedURLException error) { log.severe(errorBase + error.getMessage()); } catch (InstantiationException error) { log.severe(errorBase + error.getMessage()); } catch (IllegalAccessException error) { log.severe(errorBase + error.getMessage()); } } private void maybeNotifyPlayerOfPrimaryGroupChange(String newGroupName, Player player) { if (config.simpleSynchronizationPrimaryGroupNotify) { String message = ChatColor.YELLOW + CommunityBridge.config.messages.get("group-synchronization-primary-notify-player"); message = message.replace("~GROUPNAME~", newGroupName); player.sendMessage(message); } } } // WebApplication class
true
true
private void synchronizeGroups(Player player) { String playerName = player.getName(); String direction = config.simpleSynchronizationDirection; String userID = getUserID(playerName); if (userID.equalsIgnoreCase(config.simpleSynchronizationSuperUserID)) { direction = "web"; } File playerFolder = new File(plugin.getDataFolder(), "Players"); // 1. Retrieve previous group state for forum groups and permissions groups. PlayerGroupState previousState = new PlayerGroupState(playerName, playerFolder); previousState.load(); // 2. Capture current group state PlayerGroupState currentState = new PlayerGroupState(playerName, playerFolder); currentState.generate(); // 3. Synchronize primary group state if (config.webappPrimaryGroupEnabled) { if (direction.startsWith("two") || direction.startsWith("web") && !previousState.webappPrimaryGroupID.equals(currentState.webappPrimaryGroupID)) { String formerGroupName = config.getGroupNameByGroupID(previousState.webappPrimaryGroupID); String newGroupName = config.getGroupNameByGroupID(currentState.webappPrimaryGroupID); if (newGroupName == null) { log.warning("Not changing permissions group due to permissions system group name lookup failure for web application group ID: " + currentState.webappPrimaryGroupID + ". Player '" + playerName + "' primary group state unchanged."); currentState.webappPrimaryGroupID = previousState.webappPrimaryGroupID; } else { maybeNotifyPlayerOfPrimaryGroupChange(newGroupName, player); if (CommunityBridge.permissionHandler.supportsPrimaryGroups()) { CommunityBridge.permissionHandler.setPrimaryGroup(playerName, newGroupName, formerGroupName); log.fine("Moved player '" + playerName + "' to permissions group '" + newGroupName + "'."); } else { CommunityBridge.permissionHandler.addToGroup(playerName, newGroupName); log.fine("Added pseudo-primary group '" + newGroupName + "' to player '" + playerName + "' list of permissions groups."); } } } if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && (direction.startsWith("two") || direction.startsWith("min")) && !previousState.permissionsSystemPrimaryGroupName.equals(currentState.permissionsSystemPrimaryGroupName)) { String groupID = config.getWebappGroupIDbyGroupName(currentState.permissionsSystemPrimaryGroupName); if (groupID == null) { log.warning("Not changing web application group due to web application group ID lookup failure for: " + currentState.permissionsSystemPrimaryGroupName + ". Player '" + playerName + "' primary group state unchanged."); currentState.permissionsSystemPrimaryGroupName = previousState.permissionsSystemPrimaryGroupName; } else { setPrimaryGroup(userID, groupID); log.fine("Moved player '" + playerName + "' to web application group ID '" + groupID + "'."); } } } // 4. Synchronize secondary group state if (config.webappSecondaryGroupEnabled) { if (direction.startsWith("two") || direction.startsWith("web")) { for (String groupName : previousState.permissionsSystemGroupNames) { if (!currentState.permissionsSystemGroupNames.contains(groupName) && !config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { removeGroup(userID, groupName); } } for (Iterator<String> iterator = currentState.permissionsSystemGroupNames.iterator(); iterator.hasNext();) { String groupName = iterator.next(); if (!previousState.permissionsSystemGroupNames.contains(groupName)) { String groupID = config.getWebappGroupIDbyGroupName(groupName); // Since the group is not in the mapping, we'll NOT record it as // part of the current state. That way, if the group is added to // the mapping later, we'll see it as a 'new' group and syncrhonize. if (groupID == null) { iterator.remove(); } else if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { this.setPrimaryGroup(userID, groupID); } else if (!currentState.webappPrimaryGroupID.equals(groupID) && !currentState.webappGroupIDs.contains(groupID)) { addGroup(userID, groupID, currentState.webappGroupIDs.size()); } } } } if (direction.startsWith("two") || direction.startsWith("web")) { for(String groupID : previousState.webappGroupIDs) { if (!currentState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); CommunityBridge.permissionHandler.removeFromGroup(playerName, groupName); } } for (Iterator<String> iterator = currentState.webappGroupIDs.iterator(); iterator.hasNext();) { String groupID = iterator.next(); if (!previousState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); // Since this group is not in the mapping, we shouldn't record it // This way, if the group is later added, it will be 'new' to us // and we will syncrhonize. if (groupName == null) { iterator.remove(); } else if (!currentState.permissionsSystemPrimaryGroupName.equals(groupName) && !currentState.permissionsSystemGroupNames.contains(groupName)) { CommunityBridge.permissionHandler.addToGroup(playerName, groupName); } // Check for null/primaryalreadyset/secondaryalreadyset } // if previousState contains group ID } // for each group ID in currentState } // Synchronization direction check. } // if SecondaryWebapp enabled. // 5. Save newly created state try { currentState.save(); } catch (IOException error) { log.severe("Error when saving group state for player " + playerName + ": " + error.getMessage()); } }
private void synchronizeGroups(Player player) { String playerName = player.getName(); String direction = config.simpleSynchronizationDirection; String userID = getUserID(playerName); if (userID.equalsIgnoreCase(config.simpleSynchronizationSuperUserID)) { direction = "web"; } File playerFolder = new File(plugin.getDataFolder(), "Players"); // 1. Retrieve previous group state for forum groups and permissions groups. PlayerGroupState previousState = new PlayerGroupState(playerName, playerFolder); previousState.load(); // 2. Capture current group state PlayerGroupState currentState = new PlayerGroupState(playerName, playerFolder); currentState.generate(); // 3. Synchronize primary group state if (config.webappPrimaryGroupEnabled) { if (direction.startsWith("two") || direction.startsWith("web") && !previousState.webappPrimaryGroupID.equals(currentState.webappPrimaryGroupID)) { String formerGroupName = config.getGroupNameByGroupID(previousState.webappPrimaryGroupID); String newGroupName = config.getGroupNameByGroupID(currentState.webappPrimaryGroupID); if (newGroupName == null) { log.warning("Not changing permissions group due to permissions system group name lookup failure for web application group ID: " + currentState.webappPrimaryGroupID + ". Player '" + playerName + "' primary group state unchanged."); currentState.webappPrimaryGroupID = previousState.webappPrimaryGroupID; } else { maybeNotifyPlayerOfPrimaryGroupChange(newGroupName, player); if (CommunityBridge.permissionHandler.supportsPrimaryGroups()) { CommunityBridge.permissionHandler.setPrimaryGroup(playerName, newGroupName, formerGroupName); log.fine("Moved player '" + playerName + "' to permissions group '" + newGroupName + "'."); } else { CommunityBridge.permissionHandler.addToGroup(playerName, newGroupName); log.fine("Added pseudo-primary group '" + newGroupName + "' to player '" + playerName + "' list of permissions groups."); } } } if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && (direction.startsWith("two") || direction.startsWith("min")) && !previousState.permissionsSystemPrimaryGroupName.equals(currentState.permissionsSystemPrimaryGroupName)) { String groupID = config.getWebappGroupIDbyGroupName(currentState.permissionsSystemPrimaryGroupName); if (groupID == null) { log.warning("Not changing web application group due to web application group ID lookup failure for: " + currentState.permissionsSystemPrimaryGroupName + ". Player '" + playerName + "' primary group state unchanged."); currentState.permissionsSystemPrimaryGroupName = previousState.permissionsSystemPrimaryGroupName; } else { setPrimaryGroup(userID, groupID); log.fine("Moved player '" + playerName + "' to web application group ID '" + groupID + "'."); } } } // 4. Synchronize secondary group state if (config.webappSecondaryGroupEnabled) { if (direction.startsWith("two") || direction.startsWith("min")) { for (String groupName : previousState.permissionsSystemGroupNames) { if (!currentState.permissionsSystemGroupNames.contains(groupName) && !config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { removeGroup(userID, groupName); } } for (Iterator<String> iterator = currentState.permissionsSystemGroupNames.iterator(); iterator.hasNext();) { String groupName = iterator.next(); if (!previousState.permissionsSystemGroupNames.contains(groupName)) { String groupID = config.getWebappGroupIDbyGroupName(groupName); // Since the group is not in the mapping, we'll NOT record it as // part of the current state. That way, if the group is added to // the mapping later, we'll see it as a 'new' group and syncrhonize. if (groupID == null) { iterator.remove(); } else if (CommunityBridge.permissionHandler.supportsPrimaryGroups() && config.simpleSynchronizationGroupsTreatedAsPrimary.contains(groupName)) { this.setPrimaryGroup(userID, groupID); } else if (!currentState.webappPrimaryGroupID.equals(groupID) && !currentState.webappGroupIDs.contains(groupID)) { addGroup(userID, groupID, currentState.webappGroupIDs.size()); } } } } if (direction.startsWith("two") || direction.startsWith("web")) { for(String groupID : previousState.webappGroupIDs) { if (!currentState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); CommunityBridge.permissionHandler.removeFromGroup(playerName, groupName); } } for (Iterator<String> iterator = currentState.webappGroupIDs.iterator(); iterator.hasNext();) { String groupID = iterator.next(); if (!previousState.webappGroupIDs.contains(groupID)) { String groupName = config.getGroupNameByGroupID(groupID); // Since this group is not in the mapping, we shouldn't record it // This way, if the group is later added, it will be 'new' to us // and we will syncrhonize. if (groupName == null) { iterator.remove(); } else if (!currentState.permissionsSystemPrimaryGroupName.equals(groupName) && !currentState.permissionsSystemGroupNames.contains(groupName)) { CommunityBridge.permissionHandler.addToGroup(playerName, groupName); } // Check for null/primaryalreadyset/secondaryalreadyset } // if previousState contains group ID } // for each group ID in currentState } // Synchronization direction check. } // if SecondaryWebapp enabled. // 5. Save newly created state try { currentState.save(); } catch (IOException error) { log.severe("Error when saving group state for player " + playerName + ": " + error.getMessage()); } }
diff --git a/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java b/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java index f5b2ce295c..0206f018e3 100644 --- a/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java +++ b/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java @@ -1,471 +1,473 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.filesystem.strategy.internal; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.io.BaseEncoding.base16; import java.io.File; import java.io.IOException; import java.util.Set; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import org.jclouds.blobstore.LocalStorageStrategy; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobBuilder; import org.jclouds.blobstore.options.ListContainerOptions; import org.jclouds.domain.Location; import org.jclouds.filesystem.predicates.validators.FilesystemBlobKeyValidator; import org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator; import org.jclouds.filesystem.reference.FilesystemConstants; import org.jclouds.filesystem.util.Utils; import org.jclouds.io.Payload; import org.jclouds.io.Payloads; import org.jclouds.logging.Logger; import org.jclouds.rest.annotations.ParamValidators; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Files; /** * * @author Alfredo "Rainbowbreeze" Morresi */ public class FilesystemStorageStrategyImpl implements LocalStorageStrategy { private static final String BACK_SLASH = "\\"; @Resource protected Logger logger = Logger.NULL; protected final Provider<BlobBuilder> blobBuilders; protected final String baseDirectory; protected final FilesystemContainerNameValidator filesystemContainerNameValidator; protected final FilesystemBlobKeyValidator filesystemBlobKeyValidator; @Inject protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders, @Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir, FilesystemContainerNameValidator filesystemContainerNameValidator, FilesystemBlobKeyValidator filesystemBlobKeyValidator) { this.blobBuilders = checkNotNull(blobBuilders, "filesystem storage strategy blobBuilders"); this.baseDirectory = checkNotNull(baseDir, "filesystem storage strategy base directory"); this.filesystemContainerNameValidator = checkNotNull(filesystemContainerNameValidator, "filesystem container name validator"); this.filesystemBlobKeyValidator = checkNotNull(filesystemBlobKeyValidator, "filesystem blob key validator"); } @Override public boolean containerExists(String container) { filesystemContainerNameValidator.validate(container); return directoryExists(container, null); } @Override public Iterable<String> getAllContainerNames() { File[] files = new File(buildPathStartingFromBaseDir()).listFiles(); if (files == null) { return ImmutableList.of(); } ImmutableList.Builder<String> containers = ImmutableList.builder(); for (File file : files) { if (file.isDirectory()) { containers.add(file.getName()); } } return containers.build(); } @Override public boolean createContainerInLocation(String container, Location location) { // TODO: implement location logger.debug("Creating container %s", container); filesystemContainerNameValidator.validate(container); return createDirectoryWithResult(container, null); } @Override public void deleteContainer(String container) { filesystemContainerNameValidator.validate(container); deleteDirectory(container, null); } @Override public void clearContainer(final String container) { clearContainer(container, ListContainerOptions.Builder.recursive()); } @Override public void clearContainer(String container, ListContainerOptions options) { filesystemContainerNameValidator.validate(container); // TODO implement options try { File containerFile = openFolder(container); File[] children = containerFile.listFiles(); if (null != children) { for (File child : children) Utils.deleteRecursively(child); } } catch (IOException e) { logger.error(e, "An error occurred while clearing container %s", container); Throwables.propagate(e); } } @Override public boolean blobExists(String container, String key) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(key); return buildPathAndChecksIfFileExists(container, key); } /** * Returns all the blobs key inside a container * * @param container * @return * @throws IOException */ @Override public Iterable<String> getBlobKeysInsideContainer(String container) throws IOException { filesystemContainerNameValidator.validate(container); // check if container exists // TODO maybe an error is more appropriate Set<String> blobNames = Sets.newHashSet(); if (!containerExists(container)) { return blobNames; } File containerFile = openFolder(container); final int containerPathLength = containerFile.getAbsolutePath().length() + 1; populateBlobKeysInContainer(containerFile, blobNames, new Function<String, String>() { @Override public String apply(String string) { return string.substring(containerPathLength); } }); return blobNames; } @Override public Blob getBlob(final String container, final String key) { BlobBuilder builder = blobBuilders.get(); builder.name(key); File file = getFileForBlobKey(container, key); try { builder.payload(file).calculateMD5(); } catch (IOException e) { logger.error("An error occurred calculating MD5 for blob %s from container ", key, container); Throwables.propagateIfPossible(e); } Blob blob = builder.build(); if (blob.getPayload().getContentMetadata().getContentMD5() != null) blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5())); return blob; } @Override public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else { - payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); + if (!payload.isRepeatable()) { + payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); + } Files.copy(payload, outputFile); } Payloads.calculateMD5(payload); String eTag = base16().lowerCase().encode(payload.getContentMetadata().getContentMD5()); return eTag; } catch (IOException ex) { if (outputFile != null) { if (!outputFile.delete()) { logger.debug("Could not delete %s", outputFile); } } throw ex; } finally { payload.release(); } } @Override public void removeBlob(final String container, final String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); logger.debug("Deleting blob %s", fileName); File fileToBeDeleted = new File(fileName); if (!fileToBeDeleted.delete()) { logger.debug("Could not delete %s", fileToBeDeleted); } // now examine if the key of the blob is a complex key (with a directory structure) // and eventually remove empty directory removeDirectoriesTreeOfBlobKey(container, blobKey); } @Override public Location getLocation(final String containerName) { return null; } @Override public String getSeparator() { return File.separator; } public boolean createContainer(String container) { filesystemContainerNameValidator.validate(container); return createContainerInLocation(container, null); } public Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name) { filesystemBlobKeyValidator.validate(name); return blobBuilders.get().name(name).build(); } /** * Returns a {@link File} object that links to the blob * * @param container * @param blobKey * @return */ public File getFileForBlobKey(String container, String blobKey) { filesystemContainerNameValidator.validate(container); filesystemBlobKeyValidator.validate(blobKey); String fileName = buildPathStartingFromBaseDir(container, blobKey); File blobFile = new File(fileName); return blobFile; } public boolean directoryExists(String container, String directory) { return buildPathAndChecksIfDirectoryExists(container, directory); } public void createDirectory(String container, String directory) { createDirectoryWithResult(container, directory); } public void deleteDirectory(String container, String directory) { // create complete dir path String fullDirPath = buildPathStartingFromBaseDir(container, directory); try { Utils.deleteRecursively(new File(fullDirPath)); } catch (IOException ex) { logger.error("An error occurred removing directory %s.", fullDirPath); Throwables.propagate(ex); } } public long countBlobs(String container, ListContainerOptions options) { // TODO throw new UnsupportedOperationException("Not supported yet."); } // ---------------------------------------------------------- Private methods private boolean buildPathAndChecksIfFileExists(String... tokens) { String path = buildPathStartingFromBaseDir(tokens); File file = new File(path); boolean exists = file.exists() || file.isFile(); return exists; } /** * Check if the file system resource whose name is obtained applying buildPath on the input path * tokens is a directory, otherwise a RuntimeException is thrown * * @param tokens * the tokens that make up the name of the resource on the file system */ private boolean buildPathAndChecksIfDirectoryExists(String... tokens) { String path = buildPathStartingFromBaseDir(tokens); File file = new File(path); boolean exists = file.exists() || file.isDirectory(); return exists; } /** * Facility method used to concatenate path tokens normalizing separators * * @param pathTokens * all the string in the proper order that must be concatenated in order to obtain the * filename * @return the resulting string */ protected String buildPathStartingFromBaseDir(String... pathTokens) { String normalizedToken = removeFileSeparatorFromBorders(normalize(baseDirectory), true); StringBuilder completePath = new StringBuilder(normalizedToken); if (pathTokens != null && pathTokens.length > 0) { for (int i = 0; i < pathTokens.length; i++) { if (pathTokens[i] != null) { normalizedToken = removeFileSeparatorFromBorders(normalize(pathTokens[i]), false); completePath.append(File.separator).append(normalizedToken); } } } return completePath.toString(); } /** * Substitutes all the file separator occurrences in the path with a file separator for the * current operative system * * @param pathToBeNormalized * @return */ private static String normalize(String pathToBeNormalized) { if (null != pathToBeNormalized && pathToBeNormalized.contains(BACK_SLASH)) { if (!BACK_SLASH.equals(File.separator)) { return pathToBeNormalized.replace(BACK_SLASH, File.separator); } } return pathToBeNormalized; } private static String denormalize(String pathToDenormalize) { if (null != pathToDenormalize && pathToDenormalize.contains("/")) { if (BACK_SLASH.equals(File.separator)) { return pathToDenormalize.replace("/", BACK_SLASH); } } return pathToDenormalize; } /** * Remove leading and trailing {@link File.separator} character from the string. * * @param pathToBeCleaned * @param remove * only trailing separator char from path * @return */ private String removeFileSeparatorFromBorders(String pathToBeCleaned, boolean onlyTrailing) { if (null == pathToBeCleaned || pathToBeCleaned.equals("")) return pathToBeCleaned; int beginIndex = 0; int endIndex = pathToBeCleaned.length(); // search for separator chars if (!onlyTrailing) { if (pathToBeCleaned.substring(0, 1).equals(File.separator)) beginIndex = 1; } if (pathToBeCleaned.substring(pathToBeCleaned.length() - 1).equals(File.separator)) endIndex--; return pathToBeCleaned.substring(beginIndex, endIndex); } /** * Removes recursively the directory structure of a complex blob key, only if the directory is * empty * * @param container * @param normalizedKey */ private void removeDirectoriesTreeOfBlobKey(String container, String blobKey) { String normalizedBlobKey = denormalize(blobKey); // exists is no path is present in the blobkey if (!normalizedBlobKey.contains(File.separator)) return; File file = new File(normalizedBlobKey); // TODO // "/media/data/works/java/amazon/jclouds/master/filesystem/aa/bb/cc/dd/eef6f0c8-0206-460b-8870-352e6019893c.txt" String parentPath = file.getParent(); // no need to manage "/" parentPath, because "/" cannot be used as start // char of blobkey if (!isNullOrEmpty(parentPath)) { // remove parent directory only it's empty File directory = new File(buildPathStartingFromBaseDir(container, parentPath)); String[] children = directory.list(); if (null == children || children.length == 0) { if (!directory.delete()) { logger.debug("Could not delete %s", directory); return; } // recursively call for removing other path removeDirectoriesTreeOfBlobKey(container, parentPath); } } } private File openFolder(String folderName) throws IOException { String baseFolderName = buildPathStartingFromBaseDir(folderName); File folder = new File(baseFolderName); if (folder.exists()) { if (!folder.isDirectory()) { throw new IOException("Resource " + baseFolderName + " isn't a folder."); } } return folder; } private static void populateBlobKeysInContainer(File directory, Set<String> blobNames, Function<String, String> function) { File[] children = directory.listFiles(); for (File child : children) { if (child.isFile()) { blobNames.add(function.apply(child.getAbsolutePath())); } else if (child.isDirectory()) { populateBlobKeysInContainer(child, blobNames, function); } } } /** * Creates a directory and returns the result * * @param container * @param directory * @return true if the directory was created, otherwise false */ protected boolean createDirectoryWithResult(String container, String directory) { String directoryFullName = buildPathStartingFromBaseDir(container, directory); logger.debug("Creating directory %s", directoryFullName); // cannot use directoryFullName, because the following method rebuild // another time the path starting from base directory if (buildPathAndChecksIfDirectoryExists(container, directory)) { logger.debug("Directory %s already exists", directoryFullName); return false; } File directoryToCreate = new File(directoryFullName); boolean result = directoryToCreate.mkdirs(); return result; } }
true
true
public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else { payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); Files.copy(payload, outputFile); } Payloads.calculateMD5(payload); String eTag = base16().lowerCase().encode(payload.getContentMetadata().getContentMD5()); return eTag; } catch (IOException ex) { if (outputFile != null) { if (!outputFile.delete()) { logger.debug("Could not delete %s", outputFile); } } throw ex; } finally { payload.release(); } }
public String putBlob(final String containerName, final Blob blob) throws IOException { String blobKey = blob.getMetadata().getName(); Payload payload = blob.getPayload(); filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else { if (!payload.isRepeatable()) { payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); } Files.copy(payload, outputFile); } Payloads.calculateMD5(payload); String eTag = base16().lowerCase().encode(payload.getContentMetadata().getContentMD5()); return eTag; } catch (IOException ex) { if (outputFile != null) { if (!outputFile.delete()) { logger.debug("Could not delete %s", outputFile); } } throw ex; } finally { payload.release(); } }
diff --git a/Source/com/drew/lang/RandomAccessStreamReader.java b/Source/com/drew/lang/RandomAccessStreamReader.java index 92c18cb..c29c20c 100644 --- a/Source/com/drew/lang/RandomAccessStreamReader.java +++ b/Source/com/drew/lang/RandomAccessStreamReader.java @@ -1,199 +1,200 @@ /* * Copyright 2002-2012 Drew Noakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * More information about this project is available at: * * http://drewnoakes.com/code/exif/ * http://code.google.com/p/metadata-extractor/ */ package com.drew.lang; import com.drew.lang.annotations.NotNull; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * @author Drew Noakes http://drewnoakes.com */ public class RandomAccessStreamReader extends RandomAccessReader { private final static int DEFAULT_CHUNK_LENGTH = 2 * 1024; @NotNull private final InputStream _stream; private final int _chunkLength; private final ArrayList<byte[]> _chunks = new ArrayList<byte[]>(); private boolean _isStreamFinished; private int _streamLength; public RandomAccessStreamReader(@NotNull InputStream stream) { this(stream, DEFAULT_CHUNK_LENGTH); } @SuppressWarnings("ConstantConditions") public RandomAccessStreamReader(@NotNull InputStream stream, int chunkLength) { if (stream == null) throw new NullPointerException(); if (chunkLength <= 0) throw new IllegalArgumentException("chunkLength must be greater than zero"); _chunkLength = chunkLength; _stream = stream; } /** * Reads to the end of the stream, in order to determine the total number of bytes. * In general, this is not a good idea for this implementation of {@link RandomAccessReader}. * * @return the length of the data source, in bytes. */ @Override public long getLength() throws BufferBoundsException { isValidIndex(Integer.MAX_VALUE, 1); assert(_isStreamFinished); return _streamLength; } /** * Ensures that the buffered bytes extend to cover the specified index. If not, an attempt is made * to read to that point. * <p/> * If the stream ends before the point is reached, a {@link BufferBoundsException} is raised. * * @param index the index from which the required bytes start * @param bytesRequested the number of bytes which are required * @throws BufferBoundsException if the stream ends before the required number of bytes are acquired */ @Override protected void validateIndex(int index, int bytesRequested) throws BufferBoundsException { if (index < 0) { throw new BufferBoundsException(String.format("Attempt to read from buffer using a negative index (%d)", index)); } else if (bytesRequested < 0) { throw new BufferBoundsException("Number of requested bytes must be zero or greater"); } else if ((long)index + bytesRequested - 1 > Integer.MAX_VALUE) { throw new BufferBoundsException(String.format("Number of requested bytes summed with starting index exceed maximum range of signed 32 bit integers (requested index: %d, requested count: %d)", index, bytesRequested)); } if (!isValidIndex(index, bytesRequested)) { assert(_isStreamFinished); // TODO test that can continue using an instance of this type after this exception throw new BufferBoundsException(index, bytesRequested, _streamLength); } } @Override protected boolean isValidIndex(int index, int bytesRequested) throws BufferBoundsException { if (index < 0 || bytesRequested < 0) { return false; } long endIndexLong = (long)index + bytesRequested - 1; if (endIndexLong > Integer.MAX_VALUE) { return false; } int endIndex = (int)endIndexLong; if (_isStreamFinished) { return endIndex < _streamLength; } int chunkIndex = endIndex / _chunkLength; // TODO test loading several chunks for a single request while (chunkIndex >= _chunks.size()) { assert (!_isStreamFinished); byte[] chunk = new byte[_chunkLength]; int totalBytesRead = 0; while (!_isStreamFinished && totalBytesRead != _chunkLength) { int bytesRead; try { bytesRead = _stream.read(chunk, totalBytesRead, _chunkLength - totalBytesRead); } catch (IOException e) { throw new BufferBoundsException("IOException reading from stream", e); } if (bytesRead == -1) { // the stream has ended, which may be ok _isStreamFinished = true; _streamLength = _chunks.size() * _chunkLength + totalBytesRead; // check we have enough bytes for the requested index if (endIndex >= _streamLength) { + _chunks.add(chunk); return false; } } else { totalBytesRead += bytesRead; } } _chunks.add(chunk); } return true; } @Override protected byte getByte(int index) { assert(index >= 0); final int chunkIndex = index / _chunkLength; final int innerIndex = index % _chunkLength; final byte[] chunk = _chunks.get(chunkIndex); return chunk[innerIndex]; } @NotNull @Override public byte[] getBytes(int index, int count) throws BufferBoundsException { validateIndex(index, count); byte[] bytes = new byte[count]; int remaining = count; int fromIndex = index; int toIndex = 0; while (remaining != 0) { int fromChunkIndex = fromIndex / _chunkLength; int fromInnerIndex = fromIndex % _chunkLength; int length = Math.min(remaining, _chunkLength - fromInnerIndex); byte[] chunk = _chunks.get(fromChunkIndex); System.arraycopy(chunk, fromInnerIndex, bytes, toIndex, length); remaining -= length; fromIndex += length; toIndex += length; } return bytes; } }
true
true
protected boolean isValidIndex(int index, int bytesRequested) throws BufferBoundsException { if (index < 0 || bytesRequested < 0) { return false; } long endIndexLong = (long)index + bytesRequested - 1; if (endIndexLong > Integer.MAX_VALUE) { return false; } int endIndex = (int)endIndexLong; if (_isStreamFinished) { return endIndex < _streamLength; } int chunkIndex = endIndex / _chunkLength; // TODO test loading several chunks for a single request while (chunkIndex >= _chunks.size()) { assert (!_isStreamFinished); byte[] chunk = new byte[_chunkLength]; int totalBytesRead = 0; while (!_isStreamFinished && totalBytesRead != _chunkLength) { int bytesRead; try { bytesRead = _stream.read(chunk, totalBytesRead, _chunkLength - totalBytesRead); } catch (IOException e) { throw new BufferBoundsException("IOException reading from stream", e); } if (bytesRead == -1) { // the stream has ended, which may be ok _isStreamFinished = true; _streamLength = _chunks.size() * _chunkLength + totalBytesRead; // check we have enough bytes for the requested index if (endIndex >= _streamLength) { return false; } } else { totalBytesRead += bytesRead; } } _chunks.add(chunk); } return true; }
protected boolean isValidIndex(int index, int bytesRequested) throws BufferBoundsException { if (index < 0 || bytesRequested < 0) { return false; } long endIndexLong = (long)index + bytesRequested - 1; if (endIndexLong > Integer.MAX_VALUE) { return false; } int endIndex = (int)endIndexLong; if (_isStreamFinished) { return endIndex < _streamLength; } int chunkIndex = endIndex / _chunkLength; // TODO test loading several chunks for a single request while (chunkIndex >= _chunks.size()) { assert (!_isStreamFinished); byte[] chunk = new byte[_chunkLength]; int totalBytesRead = 0; while (!_isStreamFinished && totalBytesRead != _chunkLength) { int bytesRead; try { bytesRead = _stream.read(chunk, totalBytesRead, _chunkLength - totalBytesRead); } catch (IOException e) { throw new BufferBoundsException("IOException reading from stream", e); } if (bytesRead == -1) { // the stream has ended, which may be ok _isStreamFinished = true; _streamLength = _chunks.size() * _chunkLength + totalBytesRead; // check we have enough bytes for the requested index if (endIndex >= _streamLength) { _chunks.add(chunk); return false; } } else { totalBytesRead += bytesRead; } } _chunks.add(chunk); } return true; }
diff --git a/PuzzleApplet.java b/PuzzleApplet.java index 23eda81b..f401ecf6 100644 --- a/PuzzleApplet.java +++ b/PuzzleApplet.java @@ -1,614 +1,612 @@ /* * PuzzleApplet.java: NestedVM applet for the puzzle collection */ import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.util.*; import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.Timer; import java.util.List; import org.ibex.nestedvm.Runtime; public class PuzzleApplet extends JApplet implements Runtime.CallJavaCB { private static final long serialVersionUID = 1L; private static final int CFG_SETTINGS = 0, CFG_SEED = 1, CFG_DESC = 2, LEFT_BUTTON = 0x0200, MIDDLE_BUTTON = 0x201, RIGHT_BUTTON = 0x202, LEFT_DRAG = 0x203, MIDDLE_DRAG = 0x204, RIGHT_DRAG = 0x205, LEFT_RELEASE = 0x206, CURSOR_UP = 0x209, CURSOR_DOWN = 0x20a, CURSOR_LEFT = 0x20b, CURSOR_RIGHT = 0x20c, MOD_CTRL = 0x1000, MOD_SHFT = 0x2000, MOD_NUM_KEYPAD = 0x4000, ALIGN_VCENTRE = 0x100, ALIGN_HCENTRE = 0x001, ALIGN_HRIGHT = 0x002, C_STRING = 0, C_CHOICES = 1, C_BOOLEAN = 2; private JFrame mainWindow; private JMenu typeMenu; private JMenuItem solveCommand; private Color[] colors; private JLabel statusBar; private PuzzlePanel pp; private Runtime runtime; private String[] puzzle_args; private Graphics2D gg; private Timer timer; private int xarg1, xarg2, xarg3; private int[] xPoints, yPoints; private BufferedImage[] blitters = new BufferedImage[512]; private ConfigDialog dlg; static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } } public void init() { try { Container cp = getContentPane(); cp.setLayout(new BorderLayout()); runtime = (Runtime) Class.forName("PuzzleEngine").newInstance(); runtime.setCallJavaCB(this); JMenuBar menubar = new JMenuBar(); JMenu jm; menubar.add(jm = new JMenu("Game")); addMenuItemWithKey(jm, "New", 'n'); addMenuItemCallback(jm, "Restart", "jcallback_restart_event"); addMenuItemCallback(jm, "Specific...", "jcallback_config_event", CFG_DESC); addMenuItemCallback(jm, "Random Seed...", "jcallback_config_event", CFG_SEED); jm.addSeparator(); addMenuItemWithKey(jm, "Undo", 'u'); addMenuItemWithKey(jm, "Redo", 'r'); jm.addSeparator(); solveCommand = addMenuItemCallback(jm, "Solve", "jcallback_solve_event"); solveCommand.setEnabled(false); if (mainWindow != null) { jm.addSeparator(); addMenuItemWithKey(jm, "Exit", 'q'); } menubar.add(typeMenu = new JMenu("Type")); typeMenu.setVisible(false); menubar.add(jm = new JMenu("Help")); addMenuItemCallback(jm, "About", "jcallback_about_event"); setJMenuBar(menubar); cp.add(pp = new PuzzlePanel(), BorderLayout.CENTER); pp.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int key = -1; int shift = e.isShiftDown() ? MOD_SHFT : 0; int ctrl = e.isControlDown() ? MOD_CTRL : 0; switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: key = shift | ctrl | CURSOR_LEFT; break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: key = shift | ctrl | CURSOR_RIGHT; break; case KeyEvent.VK_UP: case KeyEvent.VK_KP_UP: key = shift | ctrl | CURSOR_UP; break; case KeyEvent.VK_DOWN: case KeyEvent.VK_KP_DOWN: key = shift | ctrl | CURSOR_DOWN; break; case KeyEvent.VK_PAGE_UP: key = shift | ctrl | MOD_NUM_KEYPAD | '9'; break; case KeyEvent.VK_PAGE_DOWN: key = shift | ctrl | MOD_NUM_KEYPAD | '3'; break; case KeyEvent.VK_HOME: key = shift | ctrl | MOD_NUM_KEYPAD | '7'; break; case KeyEvent.VK_END: key = shift | ctrl | MOD_NUM_KEYPAD | '1'; break; default: if (e.getKeyCode() >= KeyEvent.VK_NUMPAD0 && e.getKeyCode() <=KeyEvent.VK_NUMPAD9) { key = MOD_NUM_KEYPAD | (e.getKeyCode() - KeyEvent.VK_NUMPAD0+'0'); } break; } if (key != -1) { runtimeCall("jcallback_key_event", new int[] {0, 0, key}); } } public void keyTyped(KeyEvent e) { runtimeCall("jcallback_key_event", new int[] {0, 0, e.getKeyChar()}); } }); pp.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { mousePressedReleased(e, true); } public void mousePressed(MouseEvent e) { pp.requestFocus(); mousePressedReleased(e, false); } private void mousePressedReleased(MouseEvent e, boolean released) { int button; if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0) button = MIDDLE_BUTTON; else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0) button = RIGHT_BUTTON; else if ((e.getModifiers() & (InputEvent.BUTTON1_MASK)) != 0) button = LEFT_BUTTON; else return; if (released) button += LEFT_RELEASE - LEFT_BUTTON; runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button}); } }); pp.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { int button; if ((e.getModifiers() & (InputEvent.BUTTON2_MASK | InputEvent.SHIFT_MASK)) != 0) button = MIDDLE_DRAG; else if ((e.getModifiers() & (InputEvent.BUTTON3_MASK | InputEvent.ALT_MASK)) != 0) button = RIGHT_DRAG; else button = LEFT_DRAG; runtimeCall("jcallback_key_event", new int[] {e.getX(), e.getY(), button}); } }); pp.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { handleResized(); } }); pp.setFocusable(true); pp.requestFocus(); timer = new Timer(20, new ActionListener() { public void actionPerformed(ActionEvent e) { runtimeCall("jcallback_timer_func", new int[0]); } }); String gameid; try { gameid = getParameter("game_id"); } catch (java.lang.NullPointerException ex) { gameid = null; } if (gameid == null) { puzzle_args = null; } else { puzzle_args = new String[2]; puzzle_args[0] = "puzzle"; puzzle_args[1] = gameid; } SwingUtilities.invokeLater(new Runnable() { public void run() { runtime.start(puzzle_args); runtime.execute(); } }); } catch (Exception ex) { ex.printStackTrace(); } } public void destroy() { SwingUtilities.invokeLater(new Runnable() { public void run() { runtime.execute(); if (mainWindow != null) { mainWindow.dispose(); System.exit(0); } } }); } protected void handleResized() { pp.createBackBuffer(pp.getWidth(), pp.getHeight(), colors[0]); runtimeCall("jcallback_resize", new int[] {pp.getWidth(), pp.getHeight()}); } private void addMenuItemWithKey(JMenu jm, String name, int key) { addMenuItemCallback(jm, name, "jcallback_menu_key_event", key); } private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int arg) { return addMenuItemCallback(jm, name, callback, new int[] {arg}); } private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback) { return addMenuItemCallback(jm, name, callback, new int[0]); } private JMenuItem addMenuItemCallback(JMenu jm, String name, final String callback, final int[] args) { JMenuItem jmi; if (jm == typeMenu) typeMenu.add(jmi = new JCheckBoxMenuItem(name)); else jm.add(jmi = new JMenuItem(name)); jmi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { runtimeCall(callback, args); } }); return jmi; } protected void runtimeCall(String func, int[] args) { if (runtimeCallWithResult(func, args) == 42 && mainWindow != null) { destroy(); } } protected int runtimeCallWithResult(String func, int[] args) { try { return runtime.call(func, args); } catch (Runtime.CallException ex) { ex.printStackTrace(); return 42; } } private void buildConfigureMenuItem() { if (typeMenu.isVisible()) { typeMenu.addSeparator(); } else { typeMenu.setVisible(true); } addMenuItemCallback(typeMenu, "Custom...", "jcallback_config_event", CFG_SETTINGS); } private void addTypeItem(String name, final int ptrGameParams) { typeMenu.setVisible(true); addMenuItemCallback(typeMenu, name, "jcallback_preset_event", ptrGameParams); } public int call(int cmd, int arg1, int arg2, int arg3) { try { switch(cmd) { case 0: // initialize if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1)); if ((arg2 & 1) != 0) buildConfigureMenuItem(); if ((arg2 & 2) != 0) addStatusBar(); if ((arg2 & 4) != 0) solveCommand.setEnabled(true); colors = new Color[arg3]; return 0; case 1: // Type menu item addTypeItem(runtime.cstring(arg1), arg2); return 0; case 2: // MessageBox JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE); return 0; case 3: // Resize pp.setPreferredSize(new Dimension(arg1, arg2)); if (mainWindow != null) mainWindow.pack(); handleResized(); if (mainWindow != null) mainWindow.setVisible(true); return 0; case 4: // drawing tasks switch(arg1) { case 0: String text = runtime.cstring(arg2); if (text.equals("")) text = " "; System.out.println("status '" + text + "'"); statusBar.setText(text); break; case 1: gg = pp.backBuffer.createGraphics(); if (arg2 != 0 || arg3 != 0) { gg.setColor(Color.black); gg.fillRect(0, 0, arg2, getHeight()); gg.fillRect(0, 0, getWidth(), arg3); gg.fillRect(getWidth() - arg2, 0, arg2, getHeight()); gg.fillRect(0, getHeight() - arg3, getWidth(), arg3); gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 2: gg.dispose(); pp.repaint(); break; case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break; case 4: if (arg2 == 0 && arg3 == 0) { gg.fillRect(0, 0, getWidth(), getHeight()); } else { gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 5: gg.setColor(colors[xarg3]); gg.fillRect(arg2, arg3, xarg1, xarg2); break; case 6: gg.setColor(colors[xarg3]); gg.drawLine(arg2, arg3, xarg1, xarg2); break; case 7: xPoints = new int[arg2]; yPoints = new int[arg2]; break; case 8: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillPolygon(xPoints, yPoints, xPoints.length); } gg.setColor(colors[arg2]); gg.drawPolygon(xPoints, yPoints, xPoints.length); break; case 9: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); } gg.setColor(colors[arg2]); gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); break; case 10: for(int i=0; i<blitters.length; i++) { if (blitters[i] == null) { blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR); return i; } } throw new RuntimeException("No free blitter found!"); case 11: blitters[arg2] = null; break; case 12: timer.start(); break; case 13: timer.stop(); break; } return 0; case 5: // more arguments xarg1 = arg1; xarg2 = arg2; xarg3 = arg3; return 0; case 6: // polygon vertex xPoints[arg1]=arg2; yPoints[arg1]=arg3; return 0; case 7: // string gg.setColor(colors[arg2]); { String text = runtime.cstring(arg3); Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog", Font.PLAIN, 100); int height100 = this.getFontMetrics(ft).getHeight(); ft = ft.deriveFont(arg1 * 100 / (float)height100); FontMetrics fm = this.getFontMetrics(ft); int asc = fm.getAscent(), desc = fm.getDescent(); if ((xarg3 & ALIGN_VCENTRE) != 0) xarg2 += asc - (asc+desc)/2; - else - xarg2 += asc; int wid = fm.stringWidth(text); if ((xarg3 & ALIGN_HCENTRE) != 0) xarg1 -= wid / 2; else if ((xarg3 & ALIGN_HRIGHT) != 0) xarg1 -= wid; gg.setFont(ft); gg.drawString(text, xarg1, xarg2); } return 0; case 8: // blitter_save Graphics g2 = blitters[arg1].createGraphics(); g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(), arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this); g2.dispose(); return 0; case 9: // blitter_load gg.drawImage(blitters[arg1], arg2, arg3, this); return 0; case 10: // dialog_init dlg= new ConfigDialog(this, runtime.cstring(arg1)); return 0; case 11: // dialog_add_control { int sval_ptr = arg1; int ival = arg2; int ptr = xarg1; int type=xarg2; String name = runtime.cstring(xarg3); switch(type) { case C_STRING: dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr)); break; case C_BOOLEAN: dlg.addCheckBox(ptr, name, ival != 0); break; case C_CHOICES: dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival); } } return 0; case 12: dlg.finish(); dlg = null; return 0; case 13: // tick a menu item if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1; for (int i = 0; i < typeMenu.getItemCount(); i++) { if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) { ((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i); } } return 0; default: if (cmd >= 1024 && cmd < 2048) { // palette colors[cmd-1024] = new Color(arg1, arg2, arg3); } if (cmd == 1024) { pp.setBackground(colors[0]); if (statusBar != null) statusBar.setBackground(colors[0]); this.setBackground(colors[0]); } return 0; } } catch (Throwable ex) { ex.printStackTrace(); System.exit(-1); return 0; } } private void addStatusBar() { statusBar = new JLabel("test"); statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); getContentPane().add(BorderLayout.SOUTH,statusBar); } // Standalone runner public static void main(String[] args) { final PuzzleApplet a = new PuzzleApplet(); JFrame jf = new JFrame("Loading..."); jf.getContentPane().setLayout(new BorderLayout()); jf.getContentPane().add(a, BorderLayout.CENTER); a.mainWindow=jf; a.init(); a.start(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { a.stop(); a.destroy(); } }); jf.setVisible(true); } public static class PuzzlePanel extends JPanel { private static final long serialVersionUID = 1L; protected BufferedImage backBuffer; public PuzzlePanel() { setPreferredSize(new Dimension(100,100)); createBackBuffer(100,100, Color.black); } public void createBackBuffer(int w, int h, Color bg) { if (w > 0 && h > 0) { backBuffer = new BufferedImage(w,h, BufferedImage.TYPE_3BYTE_BGR); Graphics g = backBuffer.createGraphics(); g.setColor(bg); g.fillRect(0, 0, w, h); g.dispose(); } } protected void paintComponent(Graphics g) { g.drawImage(backBuffer, 0, 0, this); } } public static class ConfigComponent { public int type; public int configItemPointer; public JComponent component; public ConfigComponent(int type, int configItemPointer, JComponent component) { this.type = type; this.configItemPointer = configItemPointer; this.component = component; } } public class ConfigDialog extends JDialog { private GridBagConstraints gbcLeft = new GridBagConstraints( GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); private GridBagConstraints gbcRight = new GridBagConstraints( GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, GridBagConstraints.REMAINDER, 1, 1.0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0); private GridBagConstraints gbcBottom = new GridBagConstraints( GridBagConstraints.RELATIVE, GridBagConstraints.RELATIVE, GridBagConstraints.REMAINDER, GridBagConstraints.REMAINDER, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0); private static final long serialVersionUID = 1L; private List components = new ArrayList(); public ConfigDialog(JApplet parent, String title) { super(JOptionPane.getFrameForComponent(parent), title, true); getContentPane().setLayout(new GridBagLayout()); } public void addTextBox(int ptr, String name, String value) { getContentPane().add(new JLabel(name), gbcLeft); JComponent c = new JTextField(value, 25); getContentPane().add(c, gbcRight); components.add(new ConfigComponent(C_STRING, ptr, c)); } public void addCheckBox(int ptr, String name, boolean selected) { JComponent c = new JCheckBox(name, selected); getContentPane().add(c, gbcRight); components.add(new ConfigComponent(C_BOOLEAN, ptr, c)); } public void addComboBox(int ptr, String name, String values, int selected) { getContentPane().add(new JLabel(name), gbcLeft); StringTokenizer st = new StringTokenizer(values.substring(1), values.substring(0,1)); JComboBox c = new JComboBox(); c.setEditable(false); while(st.hasMoreTokens()) c.addItem(st.nextToken()); c.setSelectedIndex(selected); getContentPane().add(c, gbcRight); components.add(new ConfigComponent(C_CHOICES, ptr, c)); } public void finish() { JPanel buttons = new JPanel(new GridLayout(1, 2, 5, 5)); getContentPane().add(buttons, gbcBottom); JButton b; buttons.add(b=new JButton("OK")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save(); dispose(); } }); getRootPane().setDefaultButton(b); buttons.add(b=new JButton("Cancel")); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } private void save() { for (int i = 0; i < components.size(); i++) { ConfigComponent cc = (ConfigComponent) components.get(i); switch(cc.type) { case C_STRING: JTextField jtf = (JTextField)cc.component; runtimeCall("jcallback_config_set_string", new int[] {cc.configItemPointer, runtime.strdup(jtf.getText())}); break; case C_BOOLEAN: JCheckBox jcb = (JCheckBox)cc.component; runtimeCall("jcallback_config_set_boolean", new int[] {cc.configItemPointer, jcb.isSelected()?1:0}); break; case C_CHOICES: JComboBox jcm = (JComboBox)cc.component; runtimeCall("jcallback_config_set_choice", new int[] {cc.configItemPointer, jcm.getSelectedIndex()}); break; } } runtimeCall("jcallback_config_ok", new int[0]); } } }
true
true
public int call(int cmd, int arg1, int arg2, int arg3) { try { switch(cmd) { case 0: // initialize if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1)); if ((arg2 & 1) != 0) buildConfigureMenuItem(); if ((arg2 & 2) != 0) addStatusBar(); if ((arg2 & 4) != 0) solveCommand.setEnabled(true); colors = new Color[arg3]; return 0; case 1: // Type menu item addTypeItem(runtime.cstring(arg1), arg2); return 0; case 2: // MessageBox JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE); return 0; case 3: // Resize pp.setPreferredSize(new Dimension(arg1, arg2)); if (mainWindow != null) mainWindow.pack(); handleResized(); if (mainWindow != null) mainWindow.setVisible(true); return 0; case 4: // drawing tasks switch(arg1) { case 0: String text = runtime.cstring(arg2); if (text.equals("")) text = " "; System.out.println("status '" + text + "'"); statusBar.setText(text); break; case 1: gg = pp.backBuffer.createGraphics(); if (arg2 != 0 || arg3 != 0) { gg.setColor(Color.black); gg.fillRect(0, 0, arg2, getHeight()); gg.fillRect(0, 0, getWidth(), arg3); gg.fillRect(getWidth() - arg2, 0, arg2, getHeight()); gg.fillRect(0, getHeight() - arg3, getWidth(), arg3); gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 2: gg.dispose(); pp.repaint(); break; case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break; case 4: if (arg2 == 0 && arg3 == 0) { gg.fillRect(0, 0, getWidth(), getHeight()); } else { gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 5: gg.setColor(colors[xarg3]); gg.fillRect(arg2, arg3, xarg1, xarg2); break; case 6: gg.setColor(colors[xarg3]); gg.drawLine(arg2, arg3, xarg1, xarg2); break; case 7: xPoints = new int[arg2]; yPoints = new int[arg2]; break; case 8: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillPolygon(xPoints, yPoints, xPoints.length); } gg.setColor(colors[arg2]); gg.drawPolygon(xPoints, yPoints, xPoints.length); break; case 9: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); } gg.setColor(colors[arg2]); gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); break; case 10: for(int i=0; i<blitters.length; i++) { if (blitters[i] == null) { blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR); return i; } } throw new RuntimeException("No free blitter found!"); case 11: blitters[arg2] = null; break; case 12: timer.start(); break; case 13: timer.stop(); break; } return 0; case 5: // more arguments xarg1 = arg1; xarg2 = arg2; xarg3 = arg3; return 0; case 6: // polygon vertex xPoints[arg1]=arg2; yPoints[arg1]=arg3; return 0; case 7: // string gg.setColor(colors[arg2]); { String text = runtime.cstring(arg3); Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog", Font.PLAIN, 100); int height100 = this.getFontMetrics(ft).getHeight(); ft = ft.deriveFont(arg1 * 100 / (float)height100); FontMetrics fm = this.getFontMetrics(ft); int asc = fm.getAscent(), desc = fm.getDescent(); if ((xarg3 & ALIGN_VCENTRE) != 0) xarg2 += asc - (asc+desc)/2; else xarg2 += asc; int wid = fm.stringWidth(text); if ((xarg3 & ALIGN_HCENTRE) != 0) xarg1 -= wid / 2; else if ((xarg3 & ALIGN_HRIGHT) != 0) xarg1 -= wid; gg.setFont(ft); gg.drawString(text, xarg1, xarg2); } return 0; case 8: // blitter_save Graphics g2 = blitters[arg1].createGraphics(); g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(), arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this); g2.dispose(); return 0; case 9: // blitter_load gg.drawImage(blitters[arg1], arg2, arg3, this); return 0; case 10: // dialog_init dlg= new ConfigDialog(this, runtime.cstring(arg1)); return 0; case 11: // dialog_add_control { int sval_ptr = arg1; int ival = arg2; int ptr = xarg1; int type=xarg2; String name = runtime.cstring(xarg3); switch(type) { case C_STRING: dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr)); break; case C_BOOLEAN: dlg.addCheckBox(ptr, name, ival != 0); break; case C_CHOICES: dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival); } } return 0; case 12: dlg.finish(); dlg = null; return 0; case 13: // tick a menu item if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1; for (int i = 0; i < typeMenu.getItemCount(); i++) { if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) { ((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i); } } return 0; default: if (cmd >= 1024 && cmd < 2048) { // palette colors[cmd-1024] = new Color(arg1, arg2, arg3); } if (cmd == 1024) { pp.setBackground(colors[0]); if (statusBar != null) statusBar.setBackground(colors[0]); this.setBackground(colors[0]); } return 0; } } catch (Throwable ex) { ex.printStackTrace(); System.exit(-1); return 0; } }
public int call(int cmd, int arg1, int arg2, int arg3) { try { switch(cmd) { case 0: // initialize if (mainWindow != null) mainWindow.setTitle(runtime.cstring(arg1)); if ((arg2 & 1) != 0) buildConfigureMenuItem(); if ((arg2 & 2) != 0) addStatusBar(); if ((arg2 & 4) != 0) solveCommand.setEnabled(true); colors = new Color[arg3]; return 0; case 1: // Type menu item addTypeItem(runtime.cstring(arg1), arg2); return 0; case 2: // MessageBox JOptionPane.showMessageDialog(this, runtime.cstring(arg2), runtime.cstring(arg1), arg3 == 0 ? JOptionPane.INFORMATION_MESSAGE : JOptionPane.ERROR_MESSAGE); return 0; case 3: // Resize pp.setPreferredSize(new Dimension(arg1, arg2)); if (mainWindow != null) mainWindow.pack(); handleResized(); if (mainWindow != null) mainWindow.setVisible(true); return 0; case 4: // drawing tasks switch(arg1) { case 0: String text = runtime.cstring(arg2); if (text.equals("")) text = " "; System.out.println("status '" + text + "'"); statusBar.setText(text); break; case 1: gg = pp.backBuffer.createGraphics(); if (arg2 != 0 || arg3 != 0) { gg.setColor(Color.black); gg.fillRect(0, 0, arg2, getHeight()); gg.fillRect(0, 0, getWidth(), arg3); gg.fillRect(getWidth() - arg2, 0, arg2, getHeight()); gg.fillRect(0, getHeight() - arg3, getWidth(), arg3); gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 2: gg.dispose(); pp.repaint(); break; case 3: gg.setClip(arg2, arg3, xarg1, xarg2); break; case 4: if (arg2 == 0 && arg3 == 0) { gg.fillRect(0, 0, getWidth(), getHeight()); } else { gg.setClip(arg2, arg3, getWidth()-2*arg2, getHeight()-2*arg3); } break; case 5: gg.setColor(colors[xarg3]); gg.fillRect(arg2, arg3, xarg1, xarg2); break; case 6: gg.setColor(colors[xarg3]); gg.drawLine(arg2, arg3, xarg1, xarg2); break; case 7: xPoints = new int[arg2]; yPoints = new int[arg2]; break; case 8: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillPolygon(xPoints, yPoints, xPoints.length); } gg.setColor(colors[arg2]); gg.drawPolygon(xPoints, yPoints, xPoints.length); break; case 9: if (arg3 != -1) { gg.setColor(colors[arg3]); gg.fillOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); } gg.setColor(colors[arg2]); gg.drawOval(xarg1-xarg3, xarg2-xarg3, xarg3*2, xarg3*2); break; case 10: for(int i=0; i<blitters.length; i++) { if (blitters[i] == null) { blitters[i] = new BufferedImage(arg2, arg3, BufferedImage.TYPE_3BYTE_BGR); return i; } } throw new RuntimeException("No free blitter found!"); case 11: blitters[arg2] = null; break; case 12: timer.start(); break; case 13: timer.stop(); break; } return 0; case 5: // more arguments xarg1 = arg1; xarg2 = arg2; xarg3 = arg3; return 0; case 6: // polygon vertex xPoints[arg1]=arg2; yPoints[arg1]=arg3; return 0; case 7: // string gg.setColor(colors[arg2]); { String text = runtime.cstring(arg3); Font ft = new Font((xarg3 & 0x10) != 0 ? "Monospaced" : "Dialog", Font.PLAIN, 100); int height100 = this.getFontMetrics(ft).getHeight(); ft = ft.deriveFont(arg1 * 100 / (float)height100); FontMetrics fm = this.getFontMetrics(ft); int asc = fm.getAscent(), desc = fm.getDescent(); if ((xarg3 & ALIGN_VCENTRE) != 0) xarg2 += asc - (asc+desc)/2; int wid = fm.stringWidth(text); if ((xarg3 & ALIGN_HCENTRE) != 0) xarg1 -= wid / 2; else if ((xarg3 & ALIGN_HRIGHT) != 0) xarg1 -= wid; gg.setFont(ft); gg.drawString(text, xarg1, xarg2); } return 0; case 8: // blitter_save Graphics g2 = blitters[arg1].createGraphics(); g2.drawImage(pp.backBuffer, 0, 0, blitters[arg1].getWidth(), blitters[arg1].getHeight(), arg2, arg3, arg2 + blitters[arg1].getWidth(), arg3 + blitters[arg1].getHeight(), this); g2.dispose(); return 0; case 9: // blitter_load gg.drawImage(blitters[arg1], arg2, arg3, this); return 0; case 10: // dialog_init dlg= new ConfigDialog(this, runtime.cstring(arg1)); return 0; case 11: // dialog_add_control { int sval_ptr = arg1; int ival = arg2; int ptr = xarg1; int type=xarg2; String name = runtime.cstring(xarg3); switch(type) { case C_STRING: dlg.addTextBox(ptr, name, runtime.cstring(sval_ptr)); break; case C_BOOLEAN: dlg.addCheckBox(ptr, name, ival != 0); break; case C_CHOICES: dlg.addComboBox(ptr, name, runtime.cstring(sval_ptr), ival); } } return 0; case 12: dlg.finish(); dlg = null; return 0; case 13: // tick a menu item if (arg1 < 0) arg1 = typeMenu.getItemCount() - 1; for (int i = 0; i < typeMenu.getItemCount(); i++) { if (typeMenu.getMenuComponent(i) instanceof JCheckBoxMenuItem) { ((JCheckBoxMenuItem)typeMenu.getMenuComponent(i)).setSelected(arg1 == i); } } return 0; default: if (cmd >= 1024 && cmd < 2048) { // palette colors[cmd-1024] = new Color(arg1, arg2, arg3); } if (cmd == 1024) { pp.setBackground(colors[0]); if (statusBar != null) statusBar.setBackground(colors[0]); this.setBackground(colors[0]); } return 0; } } catch (Throwable ex) { ex.printStackTrace(); System.exit(-1); return 0; } }
diff --git a/src/net/java/sip/communicator/plugin/statusupdate/StatusUpdateThread.java b/src/net/java/sip/communicator/plugin/statusupdate/StatusUpdateThread.java index ef1a3df89..96777a060 100644 --- a/src/net/java/sip/communicator/plugin/statusupdate/StatusUpdateThread.java +++ b/src/net/java/sip/communicator/plugin/statusupdate/StatusUpdateThread.java @@ -1,223 +1,226 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.plugin.statusupdate; import java.awt.*; import java.util.*; import net.java.sip.communicator.service.configuration.ConfigurationService; import net.java.sip.communicator.service.protocol.*; /** * A Runnable, which permanently looks at the mouse position. If the mouse is * not moved, all accounts are set to "Away" or similar states. * * @author Thomas Hofer * */ public class StatusUpdateThread implements Runnable { private boolean run = false; private Point lastPosition = null; private Map<ProtocolProviderService, PresenceStatus> lastStates = new HashMap<ProtocolProviderService, PresenceStatus>(); private static final int IDLE_TIMER = 3000; private static final int AWAY_DEFAULT_STATUS = 40; public void run() { run = true; int timer = 0; do { try { if (MouseInfo.getPointerInfo() != null) { Point currentPosition = MouseInfo.getPointerInfo() .getLocation(); if (!isNear(lastPosition, currentPosition)) { // position has changed // check, if a minor state has been automatically set // and // reset this state to the former state. ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { if (lastStates.get(protocolProviderService) != null) { PresenceStatus lastState = lastStates .get(protocolProviderService); OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); try { presence.publishPresenceStatus(lastState, ""); } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } lastStates.remove(protocolProviderService); } } timer = getTimer() * 1000 * 60; } else { // position has not changed! // get all protocols and set them to away ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); PresenceStatus status = presence .getPresenceStatus(); if (status.getStatus() < PresenceStatus.AVAILABLE_THRESHOLD) { // already (manually) set to away or lower - break; + continue; } lastStates.put(protocolProviderService, presence .getPresenceStatus()); PresenceStatus newStatus = findAwayStatus(presence); try { - presence.publishPresenceStatus(newStatus, - newStatus.getStatusName()); + if (newStatus != null) + { + presence.publishPresenceStatus(newStatus, + newStatus.getStatusName()); + } } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } } timer = IDLE_TIMER; } lastPosition = currentPosition; } Thread.sleep(timer); } catch (InterruptedException e) { } } while (run && timer > 0); } public void stop() { run = false; } /** * Finds the Away-Status of the protocols * * @param presence * @return */ private PresenceStatus findAwayStatus(OperationSetPresence presence) { Iterator statusSet = presence.getSupportedStatusSet(); PresenceStatus status = null; while (statusSet.hasNext()) { PresenceStatus possibleState = (PresenceStatus) statusSet.next(); if (possibleState.getStatus() < PresenceStatus.AVAILABLE_THRESHOLD && possibleState.getStatus() >= PresenceStatus.ONLINE_THRESHOLD) { if (status == null || (Math.abs(possibleState.getStatus() - AWAY_DEFAULT_STATUS) < Math.abs(status .getStatus() - AWAY_DEFAULT_STATUS))) { status = possibleState; } } } return status; } private int getTimer() { ConfigurationService configService = StatusUpdateActivator .getConfigService(); String e = (String) configService.getProperty(Preferences.ENABLE); if (e == null) { return 0; } try { boolean enabled = Boolean.parseBoolean(e); if (!enabled) { return 0; } } catch (NumberFormatException ex) { return 0; } String t = (String) configService.getString(Preferences.TIMER); int timer = 0; try { timer = Integer.parseInt(t); } catch (NumberFormatException ex) { return 0; } return timer; } public boolean isRunning() { return run; } private boolean isNear(Point p1, Point p2) { if (p1 == null) { return false; } if (p2 == null) { return false; } if (Math.abs(p1.x - p2.x) > 10) { return false; } if (Math.abs(p1.y - p2.y) > 10) { return false; } return true; } }
false
true
public void run() { run = true; int timer = 0; do { try { if (MouseInfo.getPointerInfo() != null) { Point currentPosition = MouseInfo.getPointerInfo() .getLocation(); if (!isNear(lastPosition, currentPosition)) { // position has changed // check, if a minor state has been automatically set // and // reset this state to the former state. ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { if (lastStates.get(protocolProviderService) != null) { PresenceStatus lastState = lastStates .get(protocolProviderService); OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); try { presence.publishPresenceStatus(lastState, ""); } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } lastStates.remove(protocolProviderService); } } timer = getTimer() * 1000 * 60; } else { // position has not changed! // get all protocols and set them to away ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); PresenceStatus status = presence .getPresenceStatus(); if (status.getStatus() < PresenceStatus.AVAILABLE_THRESHOLD) { // already (manually) set to away or lower break; } lastStates.put(protocolProviderService, presence .getPresenceStatus()); PresenceStatus newStatus = findAwayStatus(presence); try { presence.publishPresenceStatus(newStatus, newStatus.getStatusName()); } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } } timer = IDLE_TIMER; } lastPosition = currentPosition; } Thread.sleep(timer); } catch (InterruptedException e) { } } while (run && timer > 0); }
public void run() { run = true; int timer = 0; do { try { if (MouseInfo.getPointerInfo() != null) { Point currentPosition = MouseInfo.getPointerInfo() .getLocation(); if (!isNear(lastPosition, currentPosition)) { // position has changed // check, if a minor state has been automatically set // and // reset this state to the former state. ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { if (lastStates.get(protocolProviderService) != null) { PresenceStatus lastState = lastStates .get(protocolProviderService); OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); try { presence.publishPresenceStatus(lastState, ""); } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } lastStates.remove(protocolProviderService); } } timer = getTimer() * 1000 * 60; } else { // position has not changed! // get all protocols and set them to away ProtocolProviderService[] pps = StatusUpdateActivator .getProtocolProviders(); for (ProtocolProviderService protocolProviderService : pps) { OperationSetPresence presence = (OperationSetPresence) protocolProviderService .getOperationSet(OperationSetPresence.class); PresenceStatus status = presence .getPresenceStatus(); if (status.getStatus() < PresenceStatus.AVAILABLE_THRESHOLD) { // already (manually) set to away or lower continue; } lastStates.put(protocolProviderService, presence .getPresenceStatus()); PresenceStatus newStatus = findAwayStatus(presence); try { if (newStatus != null) { presence.publishPresenceStatus(newStatus, newStatus.getStatusName()); } } catch (IllegalArgumentException e) { } catch (IllegalStateException e) { } catch (OperationFailedException e) { } } timer = IDLE_TIMER; } lastPosition = currentPosition; } Thread.sleep(timer); } catch (InterruptedException e) { } } while (run && timer > 0); }
diff --git a/JMPDComm/src/org/a0z/mpd/MPDStatus.java b/JMPDComm/src/org/a0z/mpd/MPDStatus.java index 979aef86..864d1796 100644 --- a/JMPDComm/src/org/a0z/mpd/MPDStatus.java +++ b/JMPDComm/src/org/a0z/mpd/MPDStatus.java @@ -1,340 +1,341 @@ package org.a0z.mpd; import java.util.List; /** * Class representing MPD Server status. * * @author Felipe Gustavo de Almeida * @version $Id: MPDStatus.java 2941 2005-02-09 02:34:21Z galmeida $ */ public class MPDStatus { /** * MPD State: playing. */ public static final String MPD_STATE_PLAYING = "play"; /** * MPD State: stopped. */ public static final String MPD_STATE_STOPPED = "stop"; /** * MPD State: paused. */ public static final String MPD_STATE_PAUSED = "pause"; /** * MPD State: unknown. */ public static final String MPD_STATE_UNKNOWN = "unknown"; private int playlistVersion; private int playlistLength; private int song; private int songId; private int nextSong; private int nextSongId; private boolean repeat; private boolean random; private boolean updating; private boolean single; private boolean consume; private String state; private String error; private long elapsedTime; private long totalTime; private int crossfade; private int volume; private long bitrate; private int sampleRate; private int bitsPerSample; private int channels; MPDStatus() { volume = -1; bitrate = -1; playlistVersion = -1; playlistLength = -1; song = -1; songId = -1; repeat = false; random = false; state = null; error = null; elapsedTime = -1; totalTime = -1; crossfade = 0; sampleRate = 0; channels = 0; bitsPerSample = 0; updating = false; } /** * Updates the state of the MPD Server... * * @param response */ public void updateStatus(List<String> response) { // reset values this.updating = false; // read new values try { for (String line : response) { if (line.startsWith("volume:")) { this.volume = Integer.parseInt(line.substring("volume: ".length())); } else if (line.startsWith("bitrate:")) { this.bitrate = Long.parseLong(line.substring("bitrate: ".length())); } else if (line.startsWith("playlist:")) { this.playlistVersion = Integer.parseInt(line.substring("playlist: ".length())); } else if (line.startsWith("playlistlength:")) { this.playlistLength = Integer.parseInt(line.substring("playlistlength: ".length())); } else if (line.startsWith("song:")) { this.song = Integer.parseInt(line.substring("song: ".length())); } else if (line.startsWith("songid:")) { this.songId = Integer.parseInt(line.substring("songid: ".length())); } else if (line.startsWith("repeat:")) { this.repeat = "1".equals(line.substring("repeat: ".length())) ? true : false; } else if (line.startsWith("random:")) { this.random = "1".equals(line.substring("random: ".length())) ? true : false; } else if (line.startsWith("state:")) { String state = line.substring("state: ".length()); if (MPD_STATE_PAUSED.equals(state)) { this.state = MPD_STATE_PAUSED; } else if (MPD_STATE_PLAYING.equals(state)) { this.state = MPD_STATE_PLAYING; } else if (MPD_STATE_STOPPED.equals(state)) { this.state = MPD_STATE_STOPPED; } else { this.state = MPD_STATE_UNKNOWN; } } else if (line.startsWith("error:")) { this.error = line.substring("error: ".length()); } else if (line.startsWith("time:")) { String[] time = line.substring("time: ".length()).split(":"); elapsedTime = Long.parseLong(time[0]); totalTime = Long.parseLong(time[1]); } else if (line.startsWith("audio:")) { String[] audio = line.substring("audio: ".length()).split(":"); try { sampleRate = Integer.parseInt(audio[0]); bitsPerSample = Integer.parseInt(audio[1]); channels = Integer.parseInt(audio[2]); } catch (NumberFormatException e) { // Sometimes mpd sends "?" as a sampleRate or bitsPerSample, etc ... hotfix for a bugreport I had. } } else if (line.startsWith("xfade:")) { this.crossfade = Integer.parseInt(line.substring("xfade: ".length())); } else if (line.startsWith("updating_db:")) { this.updating = true; } else if (line.startsWith("nextsong:")) { this.nextSong = Integer.parseInt(line.substring("nextsong: ".length())); } else if (line.startsWith("nextsongid:")) { this.nextSongId = Integer.parseInt(line.substring("nextsongid: ".length())); } else if (line.startsWith("consume:")) { this.consume = "1".equals(line.substring("consume: ".length())) ? true : false; } else if (line.startsWith("single:")) { this.single = "1".equals(line.substring("single: ".length())) ? true : false; } else { //TODO : This floods logcat too much, will fix later //(new InvalidResponseException("unknown response: " + line)).printStackTrace(); } } } catch(RuntimeException e) { //Do nothing, these should be harmless + e.printStackTrace(); } } /** * Retrieves current track bitrate. * * @return current track bitrate. */ public long getBitrate() { return bitrate; } /** * Retrieves current track elapsed time. * * @return current track elapsed time. */ public long getElapsedTime() { return elapsedTime; } /** * Retrieves error message. * * @return error message. */ public String getError() { return error; } /** * Retrieves playlist version. * * @return playlist version. */ public int getPlaylistVersion() { return playlistVersion; } /** * Retrieves the length of the playlist. * * @return the length of the playlist. */ public int getPlaylistLength() { return playlistLength; } /** * If random is enabled return true, return false if random is disabled. * * @return true if random is enabled, false if random is disabled */ public boolean isRandom() { return random; } /** * If repeat is enabled return true, return false if repeat is disabled. * * @return true if repeat is enabled, false if repeat is disabled. */ public boolean isRepeat() { return repeat; } /** * Retrieves the process id of any database update task. * * @return the process id of any database update task. */ public boolean isUpdating() { return updating; } public boolean isSingle() { return single; } public boolean isConsume() { return consume; } /** * Retrieves current song playlist number. * * @return current song playlist number. */ public int getSongPos() { return song; } /** * Retrieves current song playlist id. * * @return current song playlist id. */ public int getSongId() { return songId; } public int getNextSongPos() { return nextSong; } public int getNextSongId() { return nextSongId; } /** * Retrieves player state. MPD_STATE_PLAYING, MPD_STATE_PAUSED, MPD_STATE_STOPPED or MPD_STATE_UNKNOWN * * @return player state. */ public String getState() { return state; } /** * Retrieves current track total time. * * @return current track total time. */ public long getTotalTime() { return totalTime; } /** * Retrieves volume (0-100). * * @return volume. */ public int getVolume() { return volume; } /** * Retrieves bits resolution from playing song. * * @return bits resolution from playing song. */ public int getBitsPerSample() { return bitsPerSample; } /** * Retrieves number of channels from playing song. * * @return number of channels from playing song. */ public int getChannels() { return channels; } /** * Retrieves current cross-fade time. * * @return current cross-fade time in seconds. */ public int getCrossfade() { return crossfade; } /** * Retrieves sample rate from playing song. * * @return sample rate from playing song. */ public int getSampleRate() { return sampleRate; } /** * Retrieves a string representation of the object. * * @return a string representation of the object. * @see java.lang.Object#toString() */ public String toString() { return "volume: " + volume + ", bitrate: " + bitrate + ", playlist: " + playlistVersion + ", playlistLength: " + playlistLength + ", song: " + song + ", songid: " + songId + ", repeat: " + repeat + ", random: " + random + ", state: " + state + ", error: " + error + ", elapsedTime: " + elapsedTime + ", totalTime: " + totalTime; } }
true
true
public void updateStatus(List<String> response) { // reset values this.updating = false; // read new values try { for (String line : response) { if (line.startsWith("volume:")) { this.volume = Integer.parseInt(line.substring("volume: ".length())); } else if (line.startsWith("bitrate:")) { this.bitrate = Long.parseLong(line.substring("bitrate: ".length())); } else if (line.startsWith("playlist:")) { this.playlistVersion = Integer.parseInt(line.substring("playlist: ".length())); } else if (line.startsWith("playlistlength:")) { this.playlistLength = Integer.parseInt(line.substring("playlistlength: ".length())); } else if (line.startsWith("song:")) { this.song = Integer.parseInt(line.substring("song: ".length())); } else if (line.startsWith("songid:")) { this.songId = Integer.parseInt(line.substring("songid: ".length())); } else if (line.startsWith("repeat:")) { this.repeat = "1".equals(line.substring("repeat: ".length())) ? true : false; } else if (line.startsWith("random:")) { this.random = "1".equals(line.substring("random: ".length())) ? true : false; } else if (line.startsWith("state:")) { String state = line.substring("state: ".length()); if (MPD_STATE_PAUSED.equals(state)) { this.state = MPD_STATE_PAUSED; } else if (MPD_STATE_PLAYING.equals(state)) { this.state = MPD_STATE_PLAYING; } else if (MPD_STATE_STOPPED.equals(state)) { this.state = MPD_STATE_STOPPED; } else { this.state = MPD_STATE_UNKNOWN; } } else if (line.startsWith("error:")) { this.error = line.substring("error: ".length()); } else if (line.startsWith("time:")) { String[] time = line.substring("time: ".length()).split(":"); elapsedTime = Long.parseLong(time[0]); totalTime = Long.parseLong(time[1]); } else if (line.startsWith("audio:")) { String[] audio = line.substring("audio: ".length()).split(":"); try { sampleRate = Integer.parseInt(audio[0]); bitsPerSample = Integer.parseInt(audio[1]); channels = Integer.parseInt(audio[2]); } catch (NumberFormatException e) { // Sometimes mpd sends "?" as a sampleRate or bitsPerSample, etc ... hotfix for a bugreport I had. } } else if (line.startsWith("xfade:")) { this.crossfade = Integer.parseInt(line.substring("xfade: ".length())); } else if (line.startsWith("updating_db:")) { this.updating = true; } else if (line.startsWith("nextsong:")) { this.nextSong = Integer.parseInt(line.substring("nextsong: ".length())); } else if (line.startsWith("nextsongid:")) { this.nextSongId = Integer.parseInt(line.substring("nextsongid: ".length())); } else if (line.startsWith("consume:")) { this.consume = "1".equals(line.substring("consume: ".length())) ? true : false; } else if (line.startsWith("single:")) { this.single = "1".equals(line.substring("single: ".length())) ? true : false; } else { //TODO : This floods logcat too much, will fix later //(new InvalidResponseException("unknown response: " + line)).printStackTrace(); } } } catch(RuntimeException e) { //Do nothing, these should be harmless } }
public void updateStatus(List<String> response) { // reset values this.updating = false; // read new values try { for (String line : response) { if (line.startsWith("volume:")) { this.volume = Integer.parseInt(line.substring("volume: ".length())); } else if (line.startsWith("bitrate:")) { this.bitrate = Long.parseLong(line.substring("bitrate: ".length())); } else if (line.startsWith("playlist:")) { this.playlistVersion = Integer.parseInt(line.substring("playlist: ".length())); } else if (line.startsWith("playlistlength:")) { this.playlistLength = Integer.parseInt(line.substring("playlistlength: ".length())); } else if (line.startsWith("song:")) { this.song = Integer.parseInt(line.substring("song: ".length())); } else if (line.startsWith("songid:")) { this.songId = Integer.parseInt(line.substring("songid: ".length())); } else if (line.startsWith("repeat:")) { this.repeat = "1".equals(line.substring("repeat: ".length())) ? true : false; } else if (line.startsWith("random:")) { this.random = "1".equals(line.substring("random: ".length())) ? true : false; } else if (line.startsWith("state:")) { String state = line.substring("state: ".length()); if (MPD_STATE_PAUSED.equals(state)) { this.state = MPD_STATE_PAUSED; } else if (MPD_STATE_PLAYING.equals(state)) { this.state = MPD_STATE_PLAYING; } else if (MPD_STATE_STOPPED.equals(state)) { this.state = MPD_STATE_STOPPED; } else { this.state = MPD_STATE_UNKNOWN; } } else if (line.startsWith("error:")) { this.error = line.substring("error: ".length()); } else if (line.startsWith("time:")) { String[] time = line.substring("time: ".length()).split(":"); elapsedTime = Long.parseLong(time[0]); totalTime = Long.parseLong(time[1]); } else if (line.startsWith("audio:")) { String[] audio = line.substring("audio: ".length()).split(":"); try { sampleRate = Integer.parseInt(audio[0]); bitsPerSample = Integer.parseInt(audio[1]); channels = Integer.parseInt(audio[2]); } catch (NumberFormatException e) { // Sometimes mpd sends "?" as a sampleRate or bitsPerSample, etc ... hotfix for a bugreport I had. } } else if (line.startsWith("xfade:")) { this.crossfade = Integer.parseInt(line.substring("xfade: ".length())); } else if (line.startsWith("updating_db:")) { this.updating = true; } else if (line.startsWith("nextsong:")) { this.nextSong = Integer.parseInt(line.substring("nextsong: ".length())); } else if (line.startsWith("nextsongid:")) { this.nextSongId = Integer.parseInt(line.substring("nextsongid: ".length())); } else if (line.startsWith("consume:")) { this.consume = "1".equals(line.substring("consume: ".length())) ? true : false; } else if (line.startsWith("single:")) { this.single = "1".equals(line.substring("single: ".length())) ? true : false; } else { //TODO : This floods logcat too much, will fix later //(new InvalidResponseException("unknown response: " + line)).printStackTrace(); } } } catch(RuntimeException e) { //Do nothing, these should be harmless e.printStackTrace(); } }
diff --git a/src/java/com/eviware/soapui/impl/wsdl/WsdlProject.java b/src/java/com/eviware/soapui/impl/wsdl/WsdlProject.java index b4f023b2a..89c5c2ecc 100644 --- a/src/java/com/eviware/soapui/impl/wsdl/WsdlProject.java +++ b/src/java/com/eviware/soapui/impl/wsdl/WsdlProject.java @@ -1,1910 +1,1909 @@ /* * soapUI, copyright (C) 2004-2010 eviware.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details at gnu.org. */ package com.eviware.soapui.impl.wsdl; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.ImageIcon; import javax.xml.namespace.QName; import org.apache.commons.ssl.OpenSSL; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import com.eviware.soapui.SoapUI; import com.eviware.soapui.config.InterfaceConfig; import com.eviware.soapui.config.MockServiceConfig; import com.eviware.soapui.config.MockServiceDocumentConfig; import com.eviware.soapui.config.ProjectConfig; import com.eviware.soapui.config.SoapuiProjectDocumentConfig; import com.eviware.soapui.config.TestSuiteConfig; import com.eviware.soapui.config.TestSuiteDocumentConfig; import com.eviware.soapui.config.TestSuiteRunTypesConfig; import com.eviware.soapui.config.TestSuiteRunTypesConfig.Enum; import com.eviware.soapui.impl.WorkspaceImpl; import com.eviware.soapui.impl.WsdlInterfaceFactory; import com.eviware.soapui.impl.rest.support.RestRequestConverter.RestConversionException; import com.eviware.soapui.impl.settings.XmlBeansSettingsImpl; import com.eviware.soapui.impl.support.AbstractInterface; import com.eviware.soapui.impl.wsdl.endpoint.DefaultEndpointStrategy; import com.eviware.soapui.impl.wsdl.mock.WsdlMockService; import com.eviware.soapui.impl.wsdl.support.PathUtils; import com.eviware.soapui.impl.wsdl.support.wsdl.UrlWsdlLoader; import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader; import com.eviware.soapui.impl.wsdl.support.wss.DefaultWssContainer; import com.eviware.soapui.impl.wsdl.testcase.WsdlProjectRunner; import com.eviware.soapui.model.ModelItem; import com.eviware.soapui.model.iface.Interface; import com.eviware.soapui.model.mock.MockService; import com.eviware.soapui.model.project.EndpointStrategy; import com.eviware.soapui.model.project.Project; import com.eviware.soapui.model.project.ProjectListener; import com.eviware.soapui.model.propertyexpansion.DefaultPropertyExpansionContext; import com.eviware.soapui.model.propertyexpansion.PropertyExpansion; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContainer; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.model.settings.Settings; import com.eviware.soapui.model.support.ModelSupport; import com.eviware.soapui.model.testsuite.ProjectRunContext; import com.eviware.soapui.model.testsuite.ProjectRunListener; import com.eviware.soapui.model.testsuite.ProjectRunner; import com.eviware.soapui.model.testsuite.TestRunnable; import com.eviware.soapui.model.testsuite.TestSuite; import com.eviware.soapui.model.testsuite.TestSuite.TestSuiteRunType; import com.eviware.soapui.settings.ProjectSettings; import com.eviware.soapui.settings.UISettings; import com.eviware.soapui.settings.WsdlSettings; import com.eviware.soapui.support.SoapUIException; import com.eviware.soapui.support.StringUtils; import com.eviware.soapui.support.Tools; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.resolver.ResolveContext; import com.eviware.soapui.support.resolver.ResolveDialog; import com.eviware.soapui.support.scripting.SoapUIScriptEngine; import com.eviware.soapui.support.scripting.SoapUIScriptEngineRegistry; import com.eviware.soapui.support.types.StringToObjectMap; /** * WSDL project implementation * * @author Ole.Matzura */ public class WsdlProject extends AbstractTestPropertyHolderWsdlModelItem<ProjectConfig> implements Project, PropertyExpansionContainer, PropertyChangeListener, TestRunnable { public final static String AFTER_LOAD_SCRIPT_PROPERTY = WsdlProject.class.getName() + "@setupScript"; public final static String BEFORE_SAVE_SCRIPT_PROPERTY = WsdlProject.class.getName() + "@tearDownScript"; public final static String RESOURCE_ROOT_PROPERTY = WsdlProject.class.getName() + "@resourceRoot"; private WorkspaceImpl workspace; protected String path; protected List<AbstractInterface<?>> interfaces = new ArrayList<AbstractInterface<?>>(); protected List<WsdlTestSuite> testSuites = new ArrayList<WsdlTestSuite>(); protected List<WsdlMockService> mockServices = new ArrayList<WsdlMockService>(); private Set<ProjectListener> projectListeners = new HashSet<ProjectListener>(); protected SoapuiProjectDocumentConfig projectDocument; private ImageIcon disabledIcon; private ImageIcon closedIcon; private ImageIcon remoteIcon; private ImageIcon openEncyptedIcon; protected EndpointStrategy endpointStrategy = new DefaultEndpointStrategy(); protected long lastModified; private boolean remote; private boolean open = true; private boolean disabled; private SoapUIScriptEngine afterLoadScriptEngine; private SoapUIScriptEngine beforeSaveScriptEngine; private PropertyExpansionContext context = new DefaultPropertyExpansionContext(this); protected DefaultWssContainer wssContainer; private String projectPassword = null; private String hermesConfig; /* * 3 state flag: 1. 0 - project not encrypted 2. 1 - encrypted , good * password, means that it could be successfully decrypted 3. -1 - encrypted, * but with bad password or no password. */ protected int encrypted; private ImageIcon closedEncyptedIcon; protected final PropertyChangeSupport pcs; private SoapUIScriptEngine afterRunScriptEngine; private SoapUIScriptEngine beforeRunScriptEngine; private Set<ProjectRunListener> runListeners = new HashSet<ProjectRunListener>(); protected final static Logger log = Logger.getLogger(WsdlProject.class); public WsdlProject() throws XmlException, IOException, SoapUIException { this((WorkspaceImpl) null); } public WsdlProject(String path) throws XmlException, IOException, SoapUIException { this(path, (WorkspaceImpl) null); } public WsdlProject(String projectFile, String projectPassword) { this(projectFile, null, true, true, null, projectPassword); } public WsdlProject(WorkspaceImpl workspace) { this(null, workspace, true); } public WsdlProject(String path, WorkspaceImpl workspace) { this(path, workspace, true); } public WsdlProject(String path, WorkspaceImpl workspace, boolean create) { this(path, workspace, create, true, null, null); } public WsdlProject(String path, WorkspaceImpl workspace, boolean create, boolean open, String tempName, String projectPassword) { super(null, workspace, "/project.gif"); pcs = new PropertyChangeSupport(this); this.workspace = workspace; this.path = path; this.projectPassword = projectPassword; for (ProjectListener listener : SoapUI.getListenerRegistry().getListeners(ProjectListener.class)) { addProjectListener(listener); } for (ProjectRunListener listener : SoapUI.getListenerRegistry().getListeners(ProjectRunListener.class)) { addProjectRunListener(listener); } try { if (path != null && open) { File file = new File(path.trim()); if (file.exists()) { try { loadProject(new URL("file:" + file.getAbsolutePath())); lastModified = file.lastModified(); } catch (MalformedURLException e) { SoapUI.logError(e); disabled = true; } } else { try { if (!PathUtils.isHttpPath(path)) SoapUI.log.info("File [" + file.getAbsolutePath() + "] does not exist, trying URL instead"); remote = true; loadProject(new URL(path)); } catch (MalformedURLException e) { SoapUI.logError(e); disabled = true; } } } } catch (SoapUIException e) { SoapUI.logError(e); disabled = true; } finally { closedIcon = UISupport.createImageIcon("/closedProject.gif"); remoteIcon = UISupport.createImageIcon("/remoteProject.gif"); disabledIcon = UISupport.createImageIcon("/disabledProject.gif"); openEncyptedIcon = UISupport.createImageIcon("/openEncryptedProject.gif"); closedEncyptedIcon = UISupport.createImageIcon("/closedEncryptedProject.gif"); this.open = open && !disabled && (this.encrypted != -1); if (projectDocument == null) { projectDocument = SoapuiProjectDocumentConfig.Factory.newInstance(); setConfig(projectDocument.addNewSoapuiProject()); if (tempName != null || path != null) getConfig().setName(StringUtils.isNullOrEmpty(tempName) ? getNameFromPath() : tempName); setPropertiesConfig(getConfig().addNewProperties()); wssContainer = new DefaultWssContainer(this, getConfig().addNewWssContainer()); // setResourceRoot("${projectDir}"); } if (getConfig() != null) { endpointStrategy.init(this); } if (getSettings() != null) { setProjectRoot(path); } addPropertyChangeListener(this); } } protected PropertyChangeSupport getPropertyChangeSupport() { return pcs; } public boolean isRemote() { return remote; } public void loadProject(URL file) throws SoapUIException { try { UISupport.setHourglassCursor(); UrlWsdlLoader loader = new UrlWsdlLoader(file.toString(), this); loader.setUseWorker(false); projectDocument = SoapuiProjectDocumentConfig.Factory.parse(loader.load()); // see if there is encoded data this.encrypted = checkForEncodedData(projectDocument.getSoapuiProject()); setConfig(projectDocument.getSoapuiProject()); // removed cached definitions if caching is disabled if (!getSettings().getBoolean(WsdlSettings.CACHE_WSDLS)) { removeDefinitionCaches(projectDocument); } log.info("Loaded project from [" + file.toString() + "]"); try { int majorVersion = Integer.parseInt(projectDocument.getSoapuiProject().getSoapuiVersion().split("\\.")[0]); if (majorVersion > Integer.parseInt(SoapUI.SOAPUI_VERSION.split("\\.")[0])) log.warn("Project '" + projectDocument.getSoapuiProject().getName() + "' is from a newer version (" + projectDocument.getSoapuiProject().getSoapuiVersion() + ") of soapUI than this (" + SoapUI.SOAPUI_VERSION + ") and parts of it may be incompatible or incorrect. " + "Saving this project with this version of soapUI may cause it to function differently."); } catch (Exception e) { } List<InterfaceConfig> interfaceConfigs = getConfig().getInterfaceList(); for (InterfaceConfig config : interfaceConfigs) { AbstractInterface<?> iface = InterfaceFactoryRegistry.build(this, config); interfaces.add(iface); } List<TestSuiteConfig> testSuiteConfigs = getConfig().getTestSuiteList(); for (TestSuiteConfig config : testSuiteConfigs) { testSuites.add(buildTestSuite(config)); } List<MockServiceConfig> mockServiceConfigs = getConfig().getMockServiceList(); for (MockServiceConfig config : mockServiceConfigs) { mockServices.add(new WsdlMockService(this, config)); } if (!getConfig().isSetWssContainer()) getConfig().addNewWssContainer(); wssContainer = new DefaultWssContainer(this, getConfig().getWssContainer()); endpointStrategy.init(this); if (!getConfig().isSetProperties()) getConfig().addNewProperties(); if (!getConfig().isSetAbortOnError()) getConfig().setAbortOnError(false); // if( !getConfig().isSetFailOnErrors() ) // getConfig().setFailOnErrors( true ); if (!getConfig().isSetRunType()) getConfig().setRunType(TestSuiteRunTypesConfig.SEQUENTIAL); setPropertiesConfig(getConfig().getProperties()); afterLoad(); } catch (Exception e) { if (e instanceof XmlException) { XmlException xe = (XmlException) e; XmlError error = xe.getError(); if (error != null) System.err.println("Error at line " + error.getLine() + ", column " + error.getColumn()); } if (e instanceof RestConversionException) { log.error("Project file needs to be updated manually, please reload the project."); throw new SoapUIException("Failed to load project from file [" + file.toString() + "]", e); } e.printStackTrace(); throw new SoapUIException("Failed to load project from file [" + file.toString() + "]", e); } finally { UISupport.resetCursor(); } } protected WsdlTestSuite buildTestSuite(TestSuiteConfig config) { return new WsdlTestSuite(this, config); } /** * Decode encrypted data and restore user/pass * * @param soapuiProject * @return 0 - not encrypted, 1 - successfull decryption , -1 error while * decrypting, bad password, no password. * @throws IOException * @throws GeneralSecurityException * @author robert nemet */ protected int checkForEncodedData(ProjectConfig soapuiProject) throws IOException, GeneralSecurityException { byte[] encryptedContent = soapuiProject.getEncryptedContent(); char[] password = null; // no encrypted data then go back if (encryptedContent == null || encryptedContent.length == 0) return 0; String projectPassword = null; if (workspace != null) { projectPassword = workspace.getProjectPassword(soapuiProject.getName()); } else { projectPassword = this.projectPassword; } if (projectPassword == null) { password = UISupport.promptPassword("Enter Password:", soapuiProject.getName()); } else { password = projectPassword.toCharArray(); } byte[] data = null; // no pass go back. if (password == null) { return -1; } try { data = OpenSSL.decrypt("des3", password, encryptedContent); } catch (Exception e) { e.printStackTrace(); return -1; } String decryptedData = new String(data, "UTF-8"); if (decryptedData != null) { if (decryptedData.length() > 0) { try { projectDocument.getSoapuiProject().set(XmlObject.Factory.parse(decryptedData)); } catch (XmlException e) { UISupport.showErrorMessage("Wrong password. Project need to be reloaded."); getWorkspace().clearProjectPassword(soapuiProject.getName()); return -1; } } } else { UISupport.showErrorMessage("Wrong project password"); getWorkspace().clearProjectPassword(soapuiProject.getName()); return -1; } projectDocument.getSoapuiProject().setEncryptedContent(null); return 1; } @Override public void afterLoad() { super.afterLoad(); try { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].afterLoad(this); } runAfterLoadScript(); } catch (Exception e) { SoapUI.logError(e); } } protected void setProjectRoot(String path) { if (path != null && projectDocument != null) { int ix = path.lastIndexOf(File.separatorChar); if (ix > 0) getSettings().setString(ProjectSettings.PROJECT_ROOT, path.substring(0, ix)); } } public void setResourceRoot(String resourceRoot) { String old = getResourceRoot(); getConfig().setResourceRoot(resourceRoot); notifyPropertyChanged(RESOURCE_ROOT_PROPERTY, old, resourceRoot); } public String getResourceRoot() { if (!getConfig().isSetResourceRoot()) getConfig().setResourceRoot(""); return getConfig().getResourceRoot(); } @Override public ImageIcon getIcon() { if (isDisabled()) return disabledIcon; else if (getEncrypted() != 0) { if (isOpen()) { return openEncyptedIcon; } else { return closedEncyptedIcon; } } else if (!isOpen()) return closedIcon; else if (isRemote()) return remoteIcon; else return super.getIcon(); } private String getNameFromPath() { int ix = path.lastIndexOf(isRemote() ? '/' : File.separatorChar); String name = ix == -1 ? path : path.substring(ix + 1); return name; } @Override public String getDescription() { if (isOpen()) return super.getDescription(); String name = getName(); if (isDisabled()) name += " - disabled [" + getPath() + "]"; else name += " - closed [" + getPath() + "]"; return name; } public WorkspaceImpl getWorkspace() { return workspace; } public AbstractInterface<?> getInterfaceAt(int index) { return interfaces.get(index); } public AbstractInterface<?> getInterfaceByName(String interfaceName) { return (AbstractInterface<?>) getWsdlModelItemByName(interfaces, interfaceName); } public AbstractInterface<?> getInterfaceByTechnicalId(String technicalId) { for (int c = 0; c < getInterfaceCount(); c++) { if (getInterfaceAt(c).getTechnicalId().equals(technicalId)) return getInterfaceAt(c); } return null; } public int getInterfaceCount() { return interfaces.size(); } public String getPath() { return path; } public boolean save() throws IOException { return save(null); } public boolean save(String folder) throws IOException { if (!isOpen() || isDisabled() || isRemote()) return true; if (path == null || isRemote()) { path = StringUtils.createFileName2( getName(), '-' ) + "-soapui-project.xml"; if (folder != null) { path = folder + File.separatorChar + path; } File file = null; while (file == null || (file.exists() && !UISupport.confirm("File [" + file.getName() + "] exists, overwrite?", "Overwrite File?"))) { file = UISupport.getFileDialogs().saveAs(this, "Save project " + getName(), ".xml", "XML Files (*.xml)", new File(path)); if (file == null) return false; } path = file.getAbsolutePath(); } File projectFile = new File(path); while (projectFile.exists() && !projectFile.canWrite()) { if (UISupport.confirm("Project file [" + path + "] can not be written to, save to new file?", "Save Project")) { projectFile = UISupport.getFileDialogs().saveAs(this, "Save project " + getName(), ".xml", "XML Files (*.xml)", projectFile); if (projectFile == null) return false; path = projectFile.getAbsolutePath(); } else return false; } // check modified if (projectFile.exists() && lastModified != 0 && lastModified < projectFile.lastModified()) { if (!UISupport.confirm("Project file for [" + getName() + "] has been modified externally, overwrite?", "Save Project")) return false; } if (projectFile.exists() && getSettings().getBoolean(UISettings.CREATE_BACKUP)) { createBackup(projectFile); } return saveIn(projectFile); } public boolean saveBackup() throws IOException { File projectFile; if (path == null || isRemote()) { projectFile = new File( StringUtils.createFileName2( getName(), '-' ) + "-soapui-project.xml" ); } else { projectFile = new File(path); } File backupFile = getBackupFile(projectFile); return saveIn(backupFile); } public boolean saveIn(File projectFile) throws IOException { long size = 0; beforeSave(); // work with copy beacuse we do not want to change working project while // working with it // if user choose save project, save all etc. SoapuiProjectDocumentConfig projectDocument = (SoapuiProjectDocumentConfig) this.projectDocument.copy(); // check for caching if (!getSettings().getBoolean(WsdlSettings.CACHE_WSDLS)) { // no caching -> create copy and remove definition cachings removeDefinitionCaches(projectDocument); } // remove project root XmlBeansSettingsImpl tempSettings = new XmlBeansSettingsImpl(this, null, projectDocument.getSoapuiProject() .getSettings()); tempSettings.clearSetting(ProjectSettings.PROJECT_ROOT); // check for encryption String passwordForEncryption = getSettings().getString(ProjectSettings.SHADOW_PASSWORD, null); // if it has encryptedContend that means it is not decrypted corectly( bad // password, etc ), so do not encrypt it again. if (projectDocument.getSoapuiProject().getEncryptedContent() == null) { if (passwordForEncryption != null) { if (passwordForEncryption.length() > 1) { // we have password so do encryption try { String data = getConfig().xmlText(); byte[] encrypted = OpenSSL.encrypt("des3", passwordForEncryption.toCharArray(), data.getBytes()); projectDocument.getSoapuiProject().setEncryptedContent(encrypted); projectDocument.getSoapuiProject().setInterfaceArray(null); projectDocument.getSoapuiProject().setTestSuiteArray(null); projectDocument.getSoapuiProject().setMockServiceArray(null); projectDocument.getSoapuiProject().unsetWssContainer(); - projectDocument.getSoapuiProject().unsetDatabaseConnectionContainer(); projectDocument.getSoapuiProject().unsetSettings(); projectDocument.getSoapuiProject().unsetProperties(); } catch (GeneralSecurityException e) { UISupport.showErrorMessage("Encryption Error"); } } else { // no password no encryption. projectDocument.getSoapuiProject().setEncryptedContent(null); } } } // end of encryption. XmlOptions options = new XmlOptions(); if (SoapUI.getSettings().getBoolean(WsdlSettings.PRETTY_PRINT_PROJECT_FILES)) options.setSavePrettyPrint(); projectDocument.getSoapuiProject().setSoapuiVersion(SoapUI.SOAPUI_VERSION); try { File tempFile = File.createTempFile("project-temp-", ".xml", projectFile.getParentFile()); // save once to make sure it can be saved FileOutputStream tempOut = new FileOutputStream(tempFile); projectDocument.save(tempOut, options); tempOut.close(); if (getSettings().getBoolean(UISettings.LINEBREAK)) { normalizeLineBreak(projectFile, tempFile); } else { // now save it for real FileOutputStream projectOut = new FileOutputStream(projectFile); projectDocument.save(projectOut, options); projectOut.close(); // delete tempFile here so we have it as backup in case second save // fails if (!tempFile.delete()) { SoapUI.getErrorLog().warn("Failed to delete temporary project file; " + tempFile.getAbsolutePath()); tempFile.deleteOnExit(); } } size = projectFile.length(); } catch (Throwable t) { SoapUI.logError(t); UISupport.showErrorMessage("Failed to save project [" + getName() + "]: " + t.toString()); return false; } lastModified = projectFile.lastModified(); log.info("Saved project [" + getName() + "] to [" + projectFile.getAbsolutePath() + " - " + size + " bytes"); setProjectRoot(getPath()); return true; } private static void normalizeLineBreak(File target, File tmpFile) { try { FileReader fr = new FileReader(tmpFile); BufferedReader in = new BufferedReader(fr); FileWriter fw = new FileWriter(target); BufferedWriter out = new BufferedWriter(fw); String line = ""; while ((line = in.readLine()) != null) { out.write(line); out.newLine(); out.flush(); } out.close(); fw.close(); in.close(); fr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!tmpFile.delete()) { SoapUI.getErrorLog().warn("Failed to delete temporary file: " + tmpFile.getAbsolutePath()); tmpFile.deleteOnExit(); } } public void beforeSave() { try { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].beforeSave(this); } runBeforeSaveScript(); } catch (Exception e) { SoapUI.logError(e); } // notify for (AbstractInterface<?> iface : interfaces) iface.beforeSave(); for (WsdlTestSuite testSuite : testSuites) testSuite.beforeSave(); for (WsdlMockService mockService : mockServices) mockService.beforeSave(); endpointStrategy.onSave(); } protected void createBackup(File projectFile) throws IOException { File backupFile = getBackupFile(projectFile); log.info("Backing up [" + projectFile + "] to [" + backupFile + "]"); Tools.copyFile(projectFile, backupFile, true); } protected File getBackupFile(File projectFile) { String backupFolderName = getSettings().getString(UISettings.BACKUP_FOLDER, ""); File backupFolder = new File(backupFolderName); if (!backupFolder.isAbsolute()) { backupFolder = new File(projectFile.getParentFile(), backupFolderName); } if (!backupFolder.exists()) backupFolder.mkdirs(); File backupFile = new File(backupFolder, projectFile.getName() + ".backup"); return backupFile; } protected void removeDefinitionCaches(SoapuiProjectDocumentConfig config) { for (InterfaceConfig ifaceConfig : config.getSoapuiProject().getInterfaceList()) { if (ifaceConfig.isSetDefinitionCache()) { log.info("Removing definition cache from interface [" + ifaceConfig.getName() + "]"); ifaceConfig.unsetDefinitionCache(); } } } public AbstractInterface<?> addNewInterface(String name, String type) { AbstractInterface<?> iface = (AbstractInterface<?>) InterfaceFactoryRegistry.createNew(this, type, name); if (iface != null) { iface.getConfig().setType(type); interfaces.add(iface); fireInterfaceAdded(iface); } return iface; } public void addProjectListener(ProjectListener listener) { projectListeners.add(listener); } public void removeProjectListener(ProjectListener listener) { projectListeners.remove(listener); } public void fireInterfaceAdded(AbstractInterface<?> iface) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].interfaceAdded(iface); } } public void fireInterfaceRemoved(AbstractInterface<?> iface) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].interfaceRemoved(iface); } } public void fireInterfaceUpdated(AbstractInterface<?> iface) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].interfaceUpdated(iface); } } public void fireTestSuiteAdded(WsdlTestSuite testSuite) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].testSuiteAdded(testSuite); } } private void fireTestSuiteMoved(WsdlTestSuite testCase, int ix, int offset) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].testSuiteMoved(testCase, ix, offset); } } public void fireTestSuiteRemoved(WsdlTestSuite testSuite) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].testSuiteRemoved(testSuite); } } public void fireMockServiceAdded(WsdlMockService mockService) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].mockServiceAdded(mockService); } } public void fireMockServiceRemoved(WsdlMockService mockService) { ProjectListener[] a = projectListeners.toArray(new ProjectListener[projectListeners.size()]); for (int c = 0; c < a.length; c++) { a[c].mockServiceRemoved(mockService); } } public void removeInterface(AbstractInterface<?> iface) { int ix = interfaces.indexOf(iface); interfaces.remove(ix); try { fireInterfaceRemoved(iface); } finally { iface.release(); getConfig().removeInterface(ix); } } public void removeTestSuite(WsdlTestSuite testSuite) { int ix = testSuites.indexOf(testSuite); testSuites.remove(ix); try { fireTestSuiteRemoved(testSuite); } finally { testSuite.release(); getConfig().removeTestSuite(ix); } } public boolean isDisabled() { return disabled; } public int getTestSuiteCount() { return testSuites.size(); } public WsdlTestSuite getTestSuiteAt(int index) { return testSuites.get(index); } public WsdlTestSuite getTestSuiteByName(String testSuiteName) { return (WsdlTestSuite) getWsdlModelItemByName(testSuites, testSuiteName); } public WsdlTestSuite addNewTestSuite(String name) { WsdlTestSuite testSuite = buildTestSuite(getConfig().addNewTestSuite()); testSuite.setName(name); testSuites.add(testSuite); fireTestSuiteAdded(testSuite); return testSuite; } public boolean isCacheDefinitions() { return getSettings().getBoolean(WsdlSettings.CACHE_WSDLS); } public void setCacheDefinitions(boolean cacheDefinitions) { getSettings().setBoolean(WsdlSettings.CACHE_WSDLS, cacheDefinitions); } public boolean saveAs(String fileName) throws IOException { if (!isOpen() || isDisabled()) return false; String oldPath = path; path = fileName; boolean result = save(); if (!result) path = oldPath; else remote = false; setProjectRoot(path); return result; } @Override public void release() { super.release(); if (isOpen()) { endpointStrategy.release(); for (WsdlTestSuite testSuite : testSuites) testSuite.release(); for (WsdlMockService mockService : mockServices) mockService.release(); for (AbstractInterface<?> iface : interfaces) iface.release(); if (wssContainer != null) { wssContainer.release(); wssContainer = null; } } projectListeners.clear(); if (afterLoadScriptEngine != null) afterLoadScriptEngine.release(); if (beforeSaveScriptEngine != null) beforeSaveScriptEngine.release(); } public WsdlMockService addNewMockService(String name) { WsdlMockService mockService = new WsdlMockService(this, getConfig().addNewMockService()); mockService.setName(name); mockServices.add(mockService); fireMockServiceAdded(mockService); return mockService; } public WsdlMockService getMockServiceAt(int index) { return mockServices.get(index); } public WsdlMockService getMockServiceByName(String mockServiceName) { return (WsdlMockService) getWsdlModelItemByName(mockServices, mockServiceName); } public int getMockServiceCount() { return mockServices.size(); } public void removeMockService(WsdlMockService mockService) { int ix = mockServices.indexOf(mockService); mockServices.remove(ix); try { fireMockServiceRemoved(mockService); } finally { mockService.release(); getConfig().removeMockService(ix); } } public List<TestSuite> getTestSuiteList() { return new ArrayList<TestSuite>(testSuites); } public List<MockService> getMockServiceList() { return new ArrayList<MockService>(mockServices); } public List<Interface> getInterfaceList() { return new ArrayList<Interface>(interfaces); } public Map<String, Interface> getInterfaces() { Map<String, Interface> result = new HashMap<String, Interface>(); for (Interface iface : interfaces) result.put(iface.getName(), iface); return result; } public Map<String, TestSuite> getTestSuites() { Map<String, TestSuite> result = new HashMap<String, TestSuite>(); for (TestSuite iface : testSuites) result.put(iface.getName(), iface); return result; } public Map<String, MockService> getMockServices() { Map<String, MockService> result = new HashMap<String, MockService>(); for (MockService mockService : mockServices) result.put(mockService.getName(), mockService); return result; } public void reload() throws SoapUIException { reload(path); } public void reload(String path) throws SoapUIException { this.path = path; getWorkspace().reloadProject(this); } public boolean hasNature(String natureId) { Settings projectSettings = getSettings(); String projectNature = projectSettings.getString(ProjectSettings.PROJECT_NATURE, null); return natureId.equals(projectNature); } public AbstractInterface<?> importInterface(AbstractInterface<?> iface, boolean importEndpoints, boolean createCopy) { iface.beforeSave(); InterfaceConfig ifaceConfig = (InterfaceConfig) iface.getConfig().copy(); ifaceConfig = (InterfaceConfig) getConfig().addNewInterface().set(ifaceConfig); AbstractInterface<?> imported = InterfaceFactoryRegistry.build(this, ifaceConfig); interfaces.add(imported); if (iface.getProject() != this && importEndpoints) { endpointStrategy.importEndpoints(iface); } if (createCopy) ModelSupport.unsetIds(imported); imported.afterLoad(); fireInterfaceAdded(imported); return imported; } public WsdlTestSuite importTestSuite(WsdlTestSuite testSuite, String name, int index, boolean createCopy, String description) { testSuite.beforeSave(); TestSuiteConfig testSuiteConfig = index == -1 ? (TestSuiteConfig) getConfig().addNewTestSuite().set( testSuite.getConfig().copy()) : (TestSuiteConfig) getConfig().insertNewTestSuite(index).set( testSuite.getConfig().copy()); testSuiteConfig.setName(name); testSuite = buildTestSuite(testSuiteConfig); if (description != null) testSuite.setDescription(description); if (index == -1) testSuites.add(testSuite); else testSuites.add(index, testSuite); if (createCopy) ModelSupport.unsetIds(testSuite); testSuite.afterLoad(); fireTestSuiteAdded(testSuite); resolveImportedTestSuite(testSuite); return testSuite; } public WsdlMockService importMockService(WsdlMockService mockService, String name, boolean createCopy, String description) { mockService.beforeSave(); MockServiceConfig mockServiceConfig = (MockServiceConfig) getConfig().addNewMockService().set( mockService.getConfig().copy()); mockServiceConfig.setName(name); if (mockServiceConfig.isSetId() && createCopy) mockServiceConfig.unsetId(); mockService = new WsdlMockService(this, mockServiceConfig); mockService.setDescription(description); mockServices.add(mockService); if (createCopy) ModelSupport.unsetIds(mockService); mockService.afterLoad(); fireMockServiceAdded(mockService); return mockService; } public EndpointStrategy getEndpointStrategy() { return endpointStrategy; } public boolean isOpen() { return open; } public List<? extends ModelItem> getChildren() { ArrayList<ModelItem> list = new ArrayList<ModelItem>(); list.addAll(getInterfaceList()); list.addAll(getTestSuiteList()); list.addAll(getMockServiceList()); return list; } public void setAfterLoadScript(String script) { String oldScript = getAfterLoadScript(); if (!getConfig().isSetAfterLoadScript()) getConfig().addNewAfterLoadScript(); getConfig().getAfterLoadScript().setStringValue(script); if (afterLoadScriptEngine != null) afterLoadScriptEngine.setScript(script); notifyPropertyChanged(AFTER_LOAD_SCRIPT_PROPERTY, oldScript, script); } public String getAfterLoadScript() { return getConfig().isSetAfterLoadScript() ? getConfig().getAfterLoadScript().getStringValue() : null; } public void setBeforeSaveScript(String script) { String oldScript = getBeforeSaveScript(); if (!getConfig().isSetBeforeSaveScript()) getConfig().addNewBeforeSaveScript(); getConfig().getBeforeSaveScript().setStringValue(script); if (beforeSaveScriptEngine != null) beforeSaveScriptEngine.setScript(script); notifyPropertyChanged(BEFORE_SAVE_SCRIPT_PROPERTY, oldScript, script); } public String getBeforeSaveScript() { return getConfig().isSetBeforeSaveScript() ? getConfig().getBeforeSaveScript().getStringValue() : null; } public Object runAfterLoadScript() throws Exception { String script = getAfterLoadScript(); if (StringUtils.isNullOrEmpty(script)) return null; if (afterLoadScriptEngine == null) { afterLoadScriptEngine = SoapUIScriptEngineRegistry.create(this); afterLoadScriptEngine.setScript(script); } afterLoadScriptEngine.setVariable("context", context); afterLoadScriptEngine.setVariable("project", this); afterLoadScriptEngine.setVariable("log", SoapUI.ensureGroovyLog()); return afterLoadScriptEngine.run(); } public Object runBeforeSaveScript() throws Exception { String script = getBeforeSaveScript(); if (StringUtils.isNullOrEmpty(script)) return null; if (beforeSaveScriptEngine == null) { beforeSaveScriptEngine = SoapUIScriptEngineRegistry.create(this); beforeSaveScriptEngine.setScript(script); } beforeSaveScriptEngine.setVariable("context", context); beforeSaveScriptEngine.setVariable("project", this); beforeSaveScriptEngine.setVariable("log", SoapUI.ensureGroovyLog()); return beforeSaveScriptEngine.run(); } public PropertyExpansionContext getContext() { return context; } public DefaultWssContainer getWssContainer() { return wssContainer; } @Override public void resolve(ResolveContext<?> context) { super.resolve(context); wssContainer.resolve(context); } public PropertyExpansion[] getPropertyExpansions() { List<PropertyExpansion> result = new ArrayList<PropertyExpansion>(); result.addAll(Arrays.asList(wssContainer.getPropertyExpansions())); // result.addAll(Arrays.asList(databaseConnectionContainer. // getPropertyExpansions())); return result.toArray(new PropertyExpansion[result.size()]); } public String getPropertiesLabel() { return "Custom Properties"; } public String getShadowPassword() { projectPassword = getSettings() == null ? projectPassword : getSettings().getString( ProjectSettings.SHADOW_PASSWORD, null); return projectPassword; } public void setShadowPassword(String password) { String oldPassword = getSettings().getString(ProjectSettings.SHADOW_PASSWORD, null); getSettings().setString(ProjectSettings.SHADOW_PASSWORD, password); this.pcs.firePropertyChange("projectPassword", oldPassword, password); } public String getHermesConfig() { hermesConfig = getSettings() == null ? hermesConfig : resolveHermesConfig(); return hermesConfig; } private String resolveHermesConfig() { String hermesConfigProperty = getSettings().getString(ProjectSettings.HERMES_CONFIG, null); if (hermesConfigProperty != null && !hermesConfigProperty.equals("")) { return hermesConfigProperty; } else if (System.getenv("HERMES_CONFIG") != null) { return System.getenv("HERMES_CONFIG"); } else { return "${#System#user.home}\\.hermes"; } } public void setHermesConfig(String hermesConfigPath) { String oldHermesConfigPath = getSettings().getString(ProjectSettings.HERMES_CONFIG, null); getSettings().setString(ProjectSettings.HERMES_CONFIG, hermesConfigPath); this.pcs.firePropertyChange("hermesConfig", oldHermesConfigPath, hermesConfigPath); } public void inspect() { if (!isOpen()) return; byte data[] = projectDocument.getSoapuiProject().getEncryptedContent(); if (data != null && data.length > 0) { try { reload(); } catch (SoapUIException e) { e.printStackTrace(); } } } public int getEncrypted() { return this.encrypted; } public int setEncrypted(int code) { return this.encrypted = code; } public void addPropertyChangeListener(PropertyChangeListener listener) { this.pcs.addPropertyChangeListener(listener); } public void propertyChange(PropertyChangeEvent evt) { if ("projectPassword".equals(evt.getPropertyName())) { if (encrypted == 0 & (evt.getOldValue() == null || ((String) evt.getOldValue()).length() == 0)) { encrypted = 1; } if (encrypted == 1 & (evt.getNewValue() == null || ((String) evt.getNewValue()).length() == 0)) { encrypted = 0; } SoapUI.getNavigator().repaint(); } } public SoapuiProjectDocumentConfig getProjectDocument() { return projectDocument; } public int getInterfaceCount(String type) { int result = 0; for (AbstractInterface<?> iface : interfaces) { if (iface.getType().equals(type)) result++; } return result; } public List<AbstractInterface<?>> getInterfaces(String type) { ArrayList<AbstractInterface<?>> result = new ArrayList<AbstractInterface<?>>(); for (AbstractInterface<?> iface : interfaces) { if (iface.getType().equals(type)) result.add(iface); } return result; } public void importTestSuite(File file) { if (!file.exists()) { UISupport.showErrorMessage("Error loading test case "); return; } TestSuiteDocumentConfig newTestSuiteConfig = null; try { newTestSuiteConfig = TestSuiteDocumentConfig.Factory.parse(file); } catch (Exception e) { SoapUI.logError(e); } if (newTestSuiteConfig == null) { UISupport.showErrorMessage("Not valild test case xml"); } else { TestSuiteConfig config = (TestSuiteConfig) projectDocument.getSoapuiProject().addNewTestSuite().set( newTestSuiteConfig.getTestSuite()); WsdlTestSuite testSuite = buildTestSuite(config); ModelSupport.unsetIds(testSuite); testSuite.afterLoad(); testSuites.add(testSuite); fireTestSuiteAdded(testSuite); resolveImportedTestSuite(testSuite); } } private void resolveImportedTestSuite(WsdlTestSuite testSuite) { ResolveDialog resolver = new ResolveDialog("Validate TestSuite", "Checks TestSuite for inconsistencies", null); resolver.setShowOkMessage(false); resolver.resolve(testSuite); } /** * @see com.eviware.soapui.impl.WsdlInterfaceFactory.importWsdl * @deprecated */ public WsdlInterface[] importWsdl(String url, boolean createRequests) throws SoapUIException { return WsdlInterfaceFactory.importWsdl(this, url, createRequests); } /** * @see com.eviware.soapui.impl.WsdlInterfaceFactory.importWsdl * @deprecated see WsdlInterfaceFactory */ public WsdlInterface[] importWsdl(String url, boolean createRequests, WsdlLoader wsdlLoader) throws SoapUIException { return WsdlInterfaceFactory.importWsdl(this, url, createRequests, null, wsdlLoader); } /** * @see com.eviware.soapui.impl.WsdlInterfaceFactory.importWsdl * @deprecated see WsdlInterfaceFactory */ public WsdlInterface[] importWsdl(String url, boolean createRequests, QName bindingName, WsdlLoader wsdlLoader) throws SoapUIException { return WsdlInterfaceFactory.importWsdl(this, url, createRequests, bindingName, wsdlLoader); } public void setDefaultScriptLanguage(String id) { getConfig().setDefaultScriptLanguage(id); } public String getDefaultScriptLanguage() { if (getConfig().isSetDefaultScriptLanguage()) return getConfig().getDefaultScriptLanguage(); else return SoapUIScriptEngineRegistry.DEFAULT_SCRIPT_ENGINE_ID; } public int getIndexOfTestSuite(TestSuite testSuite) { return testSuites.indexOf(testSuite); } public String getBeforeRunScript() { return getConfig().isSetBeforeRunScript() ? getConfig().getBeforeRunScript().getStringValue() : null; } public void setBeforeRunScript(String script) { String oldScript = getBeforeRunScript(); if (!getConfig().isSetBeforeRunScript()) getConfig().addNewBeforeRunScript(); getConfig().getBeforeRunScript().setStringValue(script); if (beforeRunScriptEngine != null) beforeRunScriptEngine.setScript(script); notifyPropertyChanged("beforeRunScript", oldScript, script); } public Object runBeforeRunScript(ProjectRunContext context, ProjectRunner runner) throws Exception { String script = getBeforeRunScript(); if (StringUtils.isNullOrEmpty(script)) return null; if (beforeRunScriptEngine == null) { beforeRunScriptEngine = SoapUIScriptEngineRegistry.create(this); beforeRunScriptEngine.setScript(script); } beforeRunScriptEngine.setVariable("runner", runner); beforeRunScriptEngine.setVariable("context", context); beforeRunScriptEngine.setVariable("project", this); beforeRunScriptEngine.setVariable("log", SoapUI.ensureGroovyLog()); return beforeRunScriptEngine.run(); } public String getAfterRunScript() { return getConfig().isSetAfterRunScript() ? getConfig().getAfterRunScript().getStringValue() : null; } public void setAfterRunScript(String script) { String oldScript = getAfterRunScript(); if (!getConfig().isSetAfterRunScript()) getConfig().addNewAfterRunScript(); getConfig().getAfterRunScript().setStringValue(script); if (afterRunScriptEngine != null) afterRunScriptEngine.setScript(script); notifyPropertyChanged("afterRunScript", oldScript, script); } public Object runAfterRunScript(ProjectRunContext context, ProjectRunner runner) throws Exception { String script = getAfterRunScript(); if (StringUtils.isNullOrEmpty(script)) return null; if (afterRunScriptEngine == null) { afterRunScriptEngine = SoapUIScriptEngineRegistry.create(this); afterRunScriptEngine.setScript(script); } afterRunScriptEngine.setVariable("runner", runner); afterRunScriptEngine.setVariable("context", context); afterRunScriptEngine.setVariable("project", this); afterRunScriptEngine.setVariable("log", SoapUI.ensureGroovyLog()); return afterRunScriptEngine.run(); } public void addProjectRunListener(ProjectRunListener projectRunListener) { runListeners.add(projectRunListener); } public void removeProjectRunListener(ProjectRunListener projectRunListener) { runListeners.remove(projectRunListener); } public WsdlProjectRunner run(StringToObjectMap context, boolean async) { WsdlProjectRunner runner = new WsdlProjectRunner(this, context); runner.start(async); return runner; } public boolean isAbortOnError() { return getConfig().getAbortOnError(); } // public boolean isFailOnErrors() // { // return getConfig().getFailOnErrors(); // } // // public void setFailOnErrors( boolean arg0 ) // { // getConfig().setFailOnErrors( arg0 ); // } public void setAbortOnError(boolean arg0) { getConfig().setAbortOnError(arg0); } public long getTimeout() { return getConfig().getTimeout(); } public void setTimeout(long timeout) { getConfig().setTimeout(timeout); } public ProjectRunListener[] getProjectRunListeners() { return runListeners.toArray(new ProjectRunListener[runListeners.size()]); } public TestSuiteRunType getRunType() { Enum runType = getConfig().getRunType(); if (TestSuiteRunTypesConfig.PARALLELL.equals(runType)) return TestSuiteRunType.PARALLEL; else return TestSuiteRunType.SEQUENTIAL; } public void setRunType(TestSuiteRunType runType) { TestSuiteRunType oldRunType = getRunType(); if (runType == TestSuiteRunType.PARALLEL && oldRunType != TestSuiteRunType.PARALLEL) { getConfig().setRunType(TestSuiteRunTypesConfig.PARALLELL); notifyPropertyChanged("runType", oldRunType, runType); } else if (runType == TestSuiteRunType.SEQUENTIAL && oldRunType != TestSuiteRunType.SEQUENTIAL) { getConfig().setRunType(TestSuiteRunTypesConfig.SEQUENTIAL); notifyPropertyChanged("runType", oldRunType, runType); } } public WsdlTestSuite moveTestSuite(int ix, int offset) { WsdlTestSuite testSuite = testSuites.get(ix); if (offset == 0) return testSuite; testSuites.remove(ix); testSuites.add(ix + offset, testSuite); TestSuiteConfig[] configs = new TestSuiteConfig[testSuites.size()]; for (int c = 0; c < testSuites.size(); c++) { if (offset > 0) { if (c < ix) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c).copy(); else if (c < (ix + offset)) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c + 1).copy(); else if (c == ix + offset) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(ix).copy(); else configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c).copy(); } else { if (c < ix + offset) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c).copy(); else if (c == ix + offset) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(ix).copy(); else if (c <= ix) configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c - 1).copy(); else configs[c] = (TestSuiteConfig) getConfig().getTestSuiteArray(c).copy(); } } getConfig().setTestSuiteArray(configs); for (int c = 0; c < configs.length; c++) { testSuites.get(c).resetConfigOnMove(getConfig().getTestSuiteArray(c)); } fireTestSuiteMoved(testSuite, ix, offset); return testSuite; } public void importMockService(File file) { if (!file.exists()) { UISupport.showErrorMessage("Error loading test case "); return; } MockServiceDocumentConfig newMockServiceConfig = null; try { newMockServiceConfig = MockServiceDocumentConfig.Factory.parse(file); } catch (Exception e) { SoapUI.logError(e); } if (newMockServiceConfig == null) { UISupport.showErrorMessage("Not valid mock service xml"); } else { MockServiceConfig config = (MockServiceConfig) projectDocument.getSoapuiProject().addNewMockService().set( newMockServiceConfig.getMockService()); WsdlMockService mockService = new WsdlMockService(this, config); ModelSupport.unsetIds(mockService); mockService.afterLoad(); mockServices.add(mockService); fireMockServiceAdded(mockService); resolveImportedMockService(mockService); } } private void resolveImportedMockService(WsdlMockService mockService) { ResolveDialog resolver = new ResolveDialog("Validate MockService", "Checks MockService for inconsistencies", null); resolver.setShowOkMessage(false); resolver.resolve(mockService); } }
true
true
public boolean saveIn(File projectFile) throws IOException { long size = 0; beforeSave(); // work with copy beacuse we do not want to change working project while // working with it // if user choose save project, save all etc. SoapuiProjectDocumentConfig projectDocument = (SoapuiProjectDocumentConfig) this.projectDocument.copy(); // check for caching if (!getSettings().getBoolean(WsdlSettings.CACHE_WSDLS)) { // no caching -> create copy and remove definition cachings removeDefinitionCaches(projectDocument); } // remove project root XmlBeansSettingsImpl tempSettings = new XmlBeansSettingsImpl(this, null, projectDocument.getSoapuiProject() .getSettings()); tempSettings.clearSetting(ProjectSettings.PROJECT_ROOT); // check for encryption String passwordForEncryption = getSettings().getString(ProjectSettings.SHADOW_PASSWORD, null); // if it has encryptedContend that means it is not decrypted corectly( bad // password, etc ), so do not encrypt it again. if (projectDocument.getSoapuiProject().getEncryptedContent() == null) { if (passwordForEncryption != null) { if (passwordForEncryption.length() > 1) { // we have password so do encryption try { String data = getConfig().xmlText(); byte[] encrypted = OpenSSL.encrypt("des3", passwordForEncryption.toCharArray(), data.getBytes()); projectDocument.getSoapuiProject().setEncryptedContent(encrypted); projectDocument.getSoapuiProject().setInterfaceArray(null); projectDocument.getSoapuiProject().setTestSuiteArray(null); projectDocument.getSoapuiProject().setMockServiceArray(null); projectDocument.getSoapuiProject().unsetWssContainer(); projectDocument.getSoapuiProject().unsetDatabaseConnectionContainer(); projectDocument.getSoapuiProject().unsetSettings(); projectDocument.getSoapuiProject().unsetProperties(); } catch (GeneralSecurityException e) { UISupport.showErrorMessage("Encryption Error"); } } else { // no password no encryption. projectDocument.getSoapuiProject().setEncryptedContent(null); } } } // end of encryption. XmlOptions options = new XmlOptions(); if (SoapUI.getSettings().getBoolean(WsdlSettings.PRETTY_PRINT_PROJECT_FILES)) options.setSavePrettyPrint(); projectDocument.getSoapuiProject().setSoapuiVersion(SoapUI.SOAPUI_VERSION); try { File tempFile = File.createTempFile("project-temp-", ".xml", projectFile.getParentFile()); // save once to make sure it can be saved FileOutputStream tempOut = new FileOutputStream(tempFile); projectDocument.save(tempOut, options); tempOut.close(); if (getSettings().getBoolean(UISettings.LINEBREAK)) { normalizeLineBreak(projectFile, tempFile); } else { // now save it for real FileOutputStream projectOut = new FileOutputStream(projectFile); projectDocument.save(projectOut, options); projectOut.close(); // delete tempFile here so we have it as backup in case second save // fails if (!tempFile.delete()) { SoapUI.getErrorLog().warn("Failed to delete temporary project file; " + tempFile.getAbsolutePath()); tempFile.deleteOnExit(); } } size = projectFile.length(); } catch (Throwable t) { SoapUI.logError(t); UISupport.showErrorMessage("Failed to save project [" + getName() + "]: " + t.toString()); return false; } lastModified = projectFile.lastModified(); log.info("Saved project [" + getName() + "] to [" + projectFile.getAbsolutePath() + " - " + size + " bytes"); setProjectRoot(getPath()); return true; }
public boolean saveIn(File projectFile) throws IOException { long size = 0; beforeSave(); // work with copy beacuse we do not want to change working project while // working with it // if user choose save project, save all etc. SoapuiProjectDocumentConfig projectDocument = (SoapuiProjectDocumentConfig) this.projectDocument.copy(); // check for caching if (!getSettings().getBoolean(WsdlSettings.CACHE_WSDLS)) { // no caching -> create copy and remove definition cachings removeDefinitionCaches(projectDocument); } // remove project root XmlBeansSettingsImpl tempSettings = new XmlBeansSettingsImpl(this, null, projectDocument.getSoapuiProject() .getSettings()); tempSettings.clearSetting(ProjectSettings.PROJECT_ROOT); // check for encryption String passwordForEncryption = getSettings().getString(ProjectSettings.SHADOW_PASSWORD, null); // if it has encryptedContend that means it is not decrypted corectly( bad // password, etc ), so do not encrypt it again. if (projectDocument.getSoapuiProject().getEncryptedContent() == null) { if (passwordForEncryption != null) { if (passwordForEncryption.length() > 1) { // we have password so do encryption try { String data = getConfig().xmlText(); byte[] encrypted = OpenSSL.encrypt("des3", passwordForEncryption.toCharArray(), data.getBytes()); projectDocument.getSoapuiProject().setEncryptedContent(encrypted); projectDocument.getSoapuiProject().setInterfaceArray(null); projectDocument.getSoapuiProject().setTestSuiteArray(null); projectDocument.getSoapuiProject().setMockServiceArray(null); projectDocument.getSoapuiProject().unsetWssContainer(); projectDocument.getSoapuiProject().unsetSettings(); projectDocument.getSoapuiProject().unsetProperties(); } catch (GeneralSecurityException e) { UISupport.showErrorMessage("Encryption Error"); } } else { // no password no encryption. projectDocument.getSoapuiProject().setEncryptedContent(null); } } } // end of encryption. XmlOptions options = new XmlOptions(); if (SoapUI.getSettings().getBoolean(WsdlSettings.PRETTY_PRINT_PROJECT_FILES)) options.setSavePrettyPrint(); projectDocument.getSoapuiProject().setSoapuiVersion(SoapUI.SOAPUI_VERSION); try { File tempFile = File.createTempFile("project-temp-", ".xml", projectFile.getParentFile()); // save once to make sure it can be saved FileOutputStream tempOut = new FileOutputStream(tempFile); projectDocument.save(tempOut, options); tempOut.close(); if (getSettings().getBoolean(UISettings.LINEBREAK)) { normalizeLineBreak(projectFile, tempFile); } else { // now save it for real FileOutputStream projectOut = new FileOutputStream(projectFile); projectDocument.save(projectOut, options); projectOut.close(); // delete tempFile here so we have it as backup in case second save // fails if (!tempFile.delete()) { SoapUI.getErrorLog().warn("Failed to delete temporary project file; " + tempFile.getAbsolutePath()); tempFile.deleteOnExit(); } } size = projectFile.length(); } catch (Throwable t) { SoapUI.logError(t); UISupport.showErrorMessage("Failed to save project [" + getName() + "]: " + t.toString()); return false; } lastModified = projectFile.lastModified(); log.info("Saved project [" + getName() + "] to [" + projectFile.getAbsolutePath() + " - " + size + " bytes"); setProjectRoot(getPath()); return true; }
diff --git a/AngularJS/src/org/angularjs/codeInsight/AngularJSProcessor.java b/AngularJS/src/org/angularjs/codeInsight/AngularJSProcessor.java index 494b09278d..5d35633f1d 100644 --- a/AngularJS/src/org/angularjs/codeInsight/AngularJSProcessor.java +++ b/AngularJS/src/org/angularjs/codeInsight/AngularJSProcessor.java @@ -1,96 +1,96 @@ package org.angularjs.codeInsight; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lang.javascript.flex.XmlBackedJSClassImpl; import com.intellij.lang.javascript.psi.JSDefinitionExpression; import com.intellij.lang.javascript.psi.JSFile; import com.intellij.lang.javascript.psi.JSNamedElement; import com.intellij.lang.javascript.psi.JSVariable; import com.intellij.lang.javascript.psi.resolve.ImplicitJSVariableImpl; import com.intellij.lang.javascript.psi.resolve.JSResolveUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.*; import com.intellij.util.Consumer; import org.angularjs.lang.psi.AngularJSAsExpression; import org.angularjs.lang.psi.AngularJSRecursiveVisitor; import org.angularjs.lang.psi.AngularJSRepeatExpression; import java.util.HashMap; import java.util.Map; /** * @author Dennis.Ushakov */ public class AngularJSProcessor { private static final Map<String, String> NG_REPEAT_IMPLICITS = new HashMap<String, String>(); static { NG_REPEAT_IMPLICITS.put("$index", "Number"); NG_REPEAT_IMPLICITS.put("$first", "Boolean"); NG_REPEAT_IMPLICITS.put("$middle", "Boolean"); NG_REPEAT_IMPLICITS.put("$last", "Boolean"); NG_REPEAT_IMPLICITS.put("$even", "Boolean"); NG_REPEAT_IMPLICITS.put("$odd", "Boolean"); } public static void process(final PsiElement element, final Consumer<JSNamedElement> consumer) { - final PsiFile hostFile = FileContextUtil.getContextFile(element); + final PsiFile hostFile = FileContextUtil.getContextFile(element.getContainingFile().getOriginalFile()); if (hostFile == null) return; final XmlFile file = (XmlFile)hostFile; final JSResolveUtil.JSInjectedFilesVisitor visitor = new JSResolveUtil.JSInjectedFilesVisitor() { @Override protected void process(JSFile file) { file.accept(new AngularJSRecursiveVisitor() { @Override public void visitJSVariable(JSVariable node) { if (scopeMatches(element, node)) { consumer.consume(node); } super.visitJSVariable(node); } @Override public void visitAngularJSAsExpression(AngularJSAsExpression asExpression) { final JSDefinitionExpression def = asExpression.getDefinition(); if (def != null && scopeMatches(element, asExpression)) { consumer.consume(def); } } @Override public void visitAngularJSRepeatExpression(AngularJSRepeatExpression repeatExpression) { if (scopeMatches(element, repeatExpression)) { for (JSDefinitionExpression def : repeatExpression.getDefinitions()) { consumer.consume(def); } for (Map.Entry<String, String> entry : NG_REPEAT_IMPLICITS.entrySet()) { consumer.consume(new ImplicitJSVariableImpl(entry.getKey(), entry.getValue(), repeatExpression)); } } super.visitAngularJSRepeatExpression(repeatExpression); } }); } }; final XmlDocument document = file.getDocument(); if (document == null) return; for (XmlTag tag : PsiTreeUtil.getChildrenOfTypeAsList(document, XmlTag.class)) { new XmlBackedJSClassImpl.InjectedScriptsVisitor(tag, null, true, true, visitor, true).go(); } } private static boolean scopeMatches(PsiElement element, PsiElement declaration) { final InjectedLanguageManager injector = InjectedLanguageManager.getInstance(element.getProject()); final XmlTagChild elementContainer = PsiTreeUtil.getNonStrictParentOfType(injector.getInjectionHost(element), XmlTag.class, XmlText.class); final XmlTagChild declarationContainer = PsiTreeUtil.getNonStrictParentOfType(injector.getInjectionHost(declaration), XmlTag.class, XmlText.class); if (elementContainer != null && declarationContainer != null) { return PsiTreeUtil.isAncestor(declarationContainer, elementContainer, true); } return true; } }
true
true
public static void process(final PsiElement element, final Consumer<JSNamedElement> consumer) { final PsiFile hostFile = FileContextUtil.getContextFile(element); if (hostFile == null) return; final XmlFile file = (XmlFile)hostFile; final JSResolveUtil.JSInjectedFilesVisitor visitor = new JSResolveUtil.JSInjectedFilesVisitor() { @Override protected void process(JSFile file) { file.accept(new AngularJSRecursiveVisitor() { @Override public void visitJSVariable(JSVariable node) { if (scopeMatches(element, node)) { consumer.consume(node); } super.visitJSVariable(node); } @Override public void visitAngularJSAsExpression(AngularJSAsExpression asExpression) { final JSDefinitionExpression def = asExpression.getDefinition(); if (def != null && scopeMatches(element, asExpression)) { consumer.consume(def); } } @Override public void visitAngularJSRepeatExpression(AngularJSRepeatExpression repeatExpression) { if (scopeMatches(element, repeatExpression)) { for (JSDefinitionExpression def : repeatExpression.getDefinitions()) { consumer.consume(def); } for (Map.Entry<String, String> entry : NG_REPEAT_IMPLICITS.entrySet()) { consumer.consume(new ImplicitJSVariableImpl(entry.getKey(), entry.getValue(), repeatExpression)); } } super.visitAngularJSRepeatExpression(repeatExpression); } }); } }; final XmlDocument document = file.getDocument(); if (document == null) return; for (XmlTag tag : PsiTreeUtil.getChildrenOfTypeAsList(document, XmlTag.class)) { new XmlBackedJSClassImpl.InjectedScriptsVisitor(tag, null, true, true, visitor, true).go(); } }
public static void process(final PsiElement element, final Consumer<JSNamedElement> consumer) { final PsiFile hostFile = FileContextUtil.getContextFile(element.getContainingFile().getOriginalFile()); if (hostFile == null) return; final XmlFile file = (XmlFile)hostFile; final JSResolveUtil.JSInjectedFilesVisitor visitor = new JSResolveUtil.JSInjectedFilesVisitor() { @Override protected void process(JSFile file) { file.accept(new AngularJSRecursiveVisitor() { @Override public void visitJSVariable(JSVariable node) { if (scopeMatches(element, node)) { consumer.consume(node); } super.visitJSVariable(node); } @Override public void visitAngularJSAsExpression(AngularJSAsExpression asExpression) { final JSDefinitionExpression def = asExpression.getDefinition(); if (def != null && scopeMatches(element, asExpression)) { consumer.consume(def); } } @Override public void visitAngularJSRepeatExpression(AngularJSRepeatExpression repeatExpression) { if (scopeMatches(element, repeatExpression)) { for (JSDefinitionExpression def : repeatExpression.getDefinitions()) { consumer.consume(def); } for (Map.Entry<String, String> entry : NG_REPEAT_IMPLICITS.entrySet()) { consumer.consume(new ImplicitJSVariableImpl(entry.getKey(), entry.getValue(), repeatExpression)); } } super.visitAngularJSRepeatExpression(repeatExpression); } }); } }; final XmlDocument document = file.getDocument(); if (document == null) return; for (XmlTag tag : PsiTreeUtil.getChildrenOfTypeAsList(document, XmlTag.class)) { new XmlBackedJSClassImpl.InjectedScriptsVisitor(tag, null, true, true, visitor, true).go(); } }
diff --git a/src/main/java/org/multibit/action/OpenWalletSubmitAction.java b/src/main/java/org/multibit/action/OpenWalletSubmitAction.java index 3a53d2f2..129e033f 100644 --- a/src/main/java/org/multibit/action/OpenWalletSubmitAction.java +++ b/src/main/java/org/multibit/action/OpenWalletSubmitAction.java @@ -1,67 +1,71 @@ /** * Copyright 2011 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.action; import java.io.File; import org.multibit.controller.MultiBitController; import org.multibit.model.Data; import org.multibit.model.DataProvider; import org.multibit.model.Item; import org.multibit.model.MultiBitModel; /** * an action to process the submit of the Open Wallet view * * @author jim * */ public class OpenWalletSubmitAction implements Action { private MultiBitController controller; public OpenWalletSubmitAction(MultiBitController controller) { this.controller = controller; } public void execute(DataProvider dataProvider) { // get the file name from the data provider and see if it has changed if (dataProvider != null) { Data data = dataProvider.getData(); if (data != null) { Item item = data.getItem(MultiBitModel.ACTIVE_WALLET_FILENAME); if (item != null && item.getNewValue() != null && !item.getNewValue().equals(item.getOriginalValue())) { String walletFilename = (String) (item.getNewValue()); // defensive check on file being a directory - should never // happen if (!(new File(walletFilename).isDirectory())) { controller.addWalletFromFilename(walletFilename); controller.getModel().setActiveWalletByFilename(walletFilename); controller.fireNewWalletCreated(); } - } + } else { + // same wallet was chosen - this fire is to stop the next open dialog being small + // TODO - make open wallet a little action on the "Your Wallets" panel + controller.fireNewWalletCreated(); + } } controller.setActionForwardToParent(); } else { // should never happen return to parent view controller.setActionForwardToParent(); } } }
true
true
public void execute(DataProvider dataProvider) { // get the file name from the data provider and see if it has changed if (dataProvider != null) { Data data = dataProvider.getData(); if (data != null) { Item item = data.getItem(MultiBitModel.ACTIVE_WALLET_FILENAME); if (item != null && item.getNewValue() != null && !item.getNewValue().equals(item.getOriginalValue())) { String walletFilename = (String) (item.getNewValue()); // defensive check on file being a directory - should never // happen if (!(new File(walletFilename).isDirectory())) { controller.addWalletFromFilename(walletFilename); controller.getModel().setActiveWalletByFilename(walletFilename); controller.fireNewWalletCreated(); } } } controller.setActionForwardToParent(); } else { // should never happen return to parent view controller.setActionForwardToParent(); } }
public void execute(DataProvider dataProvider) { // get the file name from the data provider and see if it has changed if (dataProvider != null) { Data data = dataProvider.getData(); if (data != null) { Item item = data.getItem(MultiBitModel.ACTIVE_WALLET_FILENAME); if (item != null && item.getNewValue() != null && !item.getNewValue().equals(item.getOriginalValue())) { String walletFilename = (String) (item.getNewValue()); // defensive check on file being a directory - should never // happen if (!(new File(walletFilename).isDirectory())) { controller.addWalletFromFilename(walletFilename); controller.getModel().setActiveWalletByFilename(walletFilename); controller.fireNewWalletCreated(); } } else { // same wallet was chosen - this fire is to stop the next open dialog being small // TODO - make open wallet a little action on the "Your Wallets" panel controller.fireNewWalletCreated(); } } controller.setActionForwardToParent(); } else { // should never happen return to parent view controller.setActionForwardToParent(); } }
diff --git a/src/org/zaproxy/zap/extension/saml/ui/AddNewAttributeDialog.java b/src/org/zaproxy/zap/extension/saml/ui/AddNewAttributeDialog.java index 6e86089..f6adabe 100644 --- a/src/org/zaproxy/zap/extension/saml/ui/AddNewAttributeDialog.java +++ b/src/org/zaproxy/zap/extension/saml/ui/AddNewAttributeDialog.java @@ -1,118 +1,118 @@ package org.zaproxy.zap.extension.saml.ui; import org.parosproxy.paros.view.View; import org.zaproxy.zap.extension.saml.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class AddNewAttributeDialog extends JDialog { private final JPanel contentPanel = new JPanel(); private JComboBox<Attribute> comboBoxAttribSelect; private JTextField txtAttribValues; /** * Create the dialog. */ public AddNewAttributeDialog(final DesiredAttributeChangeListener listener) { setTitle("Add New Attribute"); setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); { JPanel attribNamePanel = new JPanel(); FlowLayout flowLayout = (FlowLayout) attribNamePanel.getLayout(); flowLayout.setHgap(0); flowLayout.setAlignment(FlowLayout.LEFT); contentPanel.add(attribNamePanel, BorderLayout.NORTH); { attribNamePanel.setBorder(BorderFactory.createTitledBorder("Attribute Name")); comboBoxAttribSelect = new JComboBox<>(); try { for (Attribute attribute : SAMLConfiguration.getConfiguration().getAvailableAttributes()) { if(!listener.getDesiredAttributes().contains(attribute.getName())){ - comboBoxAttribSelect.addItem(attribute); + comboBoxAttribSelect.addItem((Attribute) attribute.clone()); } } } catch (SAMLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } catch (CloneNotSupportedException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } comboBoxAttribSelect.setMaximumRowCount(5); attribNamePanel.add(comboBoxAttribSelect); } } { JPanel attribValuesPanel = new JPanel(); contentPanel.add(attribValuesPanel, BorderLayout.CENTER); attribValuesPanel.setLayout(new BorderLayout(5, 5)); { JLabel lblAttributeValues = new JLabel("Attribute Values"); lblAttributeValues.setHorizontalAlignment(SwingConstants.LEFT); attribValuesPanel.add(lblAttributeValues, BorderLayout.NORTH); } { - JScrollPane scrollPaneAttribValues = new JScrollPane(); - attribValuesPanel.add(scrollPaneAttribValues, BorderLayout.CENTER); { txtAttribValues = new JTextField(); - scrollPaneAttribValues.setViewportView(txtAttribValues); + attribValuesPanel.add(txtAttribValues, BorderLayout.CENTER); } } } { final JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { final JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(comboBoxAttribSelect.getSelectedItem()==null){ View.getSingleton().showWarningDialog("No Attribute selected, " + "please select one from combo box"); return; } if(txtAttribValues.getText().equals("")){ JOptionPane.showMessageDialog(AddNewAttributeDialog.this,"No values given, " + "Please provide a non-empty value","Error in value", JOptionPane.OK_OPTION); return; } Attribute attribute = ((Attribute)comboBoxAttribSelect.getSelectedItem()); attribute.setValue(txtAttribValues.getText()); listener.onDesiredAttributeValueChange(attribute); AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(cancelButton); } } } public JComboBox<Attribute> getComboBoxAttribSelect() { return comboBoxAttribSelect; } public JTextField getTxtAttribValues() { return txtAttribValues; } }
false
true
public AddNewAttributeDialog(final DesiredAttributeChangeListener listener) { setTitle("Add New Attribute"); setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); { JPanel attribNamePanel = new JPanel(); FlowLayout flowLayout = (FlowLayout) attribNamePanel.getLayout(); flowLayout.setHgap(0); flowLayout.setAlignment(FlowLayout.LEFT); contentPanel.add(attribNamePanel, BorderLayout.NORTH); { attribNamePanel.setBorder(BorderFactory.createTitledBorder("Attribute Name")); comboBoxAttribSelect = new JComboBox<>(); try { for (Attribute attribute : SAMLConfiguration.getConfiguration().getAvailableAttributes()) { if(!listener.getDesiredAttributes().contains(attribute.getName())){ comboBoxAttribSelect.addItem(attribute); } } } catch (SAMLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } comboBoxAttribSelect.setMaximumRowCount(5); attribNamePanel.add(comboBoxAttribSelect); } } { JPanel attribValuesPanel = new JPanel(); contentPanel.add(attribValuesPanel, BorderLayout.CENTER); attribValuesPanel.setLayout(new BorderLayout(5, 5)); { JLabel lblAttributeValues = new JLabel("Attribute Values"); lblAttributeValues.setHorizontalAlignment(SwingConstants.LEFT); attribValuesPanel.add(lblAttributeValues, BorderLayout.NORTH); } { JScrollPane scrollPaneAttribValues = new JScrollPane(); attribValuesPanel.add(scrollPaneAttribValues, BorderLayout.CENTER); { txtAttribValues = new JTextField(); scrollPaneAttribValues.setViewportView(txtAttribValues); } } } { final JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { final JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(comboBoxAttribSelect.getSelectedItem()==null){ View.getSingleton().showWarningDialog("No Attribute selected, " + "please select one from combo box"); return; } if(txtAttribValues.getText().equals("")){ JOptionPane.showMessageDialog(AddNewAttributeDialog.this,"No values given, " + "Please provide a non-empty value","Error in value", JOptionPane.OK_OPTION); return; } Attribute attribute = ((Attribute)comboBoxAttribSelect.getSelectedItem()); attribute.setValue(txtAttribValues.getText()); listener.onDesiredAttributeValueChange(attribute); AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(cancelButton); } } }
public AddNewAttributeDialog(final DesiredAttributeChangeListener listener) { setTitle("Add New Attribute"); setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); { JPanel attribNamePanel = new JPanel(); FlowLayout flowLayout = (FlowLayout) attribNamePanel.getLayout(); flowLayout.setHgap(0); flowLayout.setAlignment(FlowLayout.LEFT); contentPanel.add(attribNamePanel, BorderLayout.NORTH); { attribNamePanel.setBorder(BorderFactory.createTitledBorder("Attribute Name")); comboBoxAttribSelect = new JComboBox<>(); try { for (Attribute attribute : SAMLConfiguration.getConfiguration().getAvailableAttributes()) { if(!listener.getDesiredAttributes().contains(attribute.getName())){ comboBoxAttribSelect.addItem((Attribute) attribute.clone()); } } } catch (SAMLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (CloneNotSupportedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } comboBoxAttribSelect.setMaximumRowCount(5); attribNamePanel.add(comboBoxAttribSelect); } } { JPanel attribValuesPanel = new JPanel(); contentPanel.add(attribValuesPanel, BorderLayout.CENTER); attribValuesPanel.setLayout(new BorderLayout(5, 5)); { JLabel lblAttributeValues = new JLabel("Attribute Values"); lblAttributeValues.setHorizontalAlignment(SwingConstants.LEFT); attribValuesPanel.add(lblAttributeValues, BorderLayout.NORTH); } { { txtAttribValues = new JTextField(); attribValuesPanel.add(txtAttribValues, BorderLayout.CENTER); } } } { final JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { final JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(comboBoxAttribSelect.getSelectedItem()==null){ View.getSingleton().showWarningDialog("No Attribute selected, " + "please select one from combo box"); return; } if(txtAttribValues.getText().equals("")){ JOptionPane.showMessageDialog(AddNewAttributeDialog.this,"No values given, " + "Please provide a non-empty value","Error in value", JOptionPane.OK_OPTION); return; } Attribute attribute = ((Attribute)comboBoxAttribSelect.getSelectedItem()); attribute.setValue(txtAttribValues.getText()); listener.onDesiredAttributeValueChange(attribute); AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AddNewAttributeDialog.this.setVisible(false); } }); buttonPane.add(cancelButton); } } }
diff --git a/bombermen2/bombermen-server/src/pt/up/fe/pt/lpoo/bombermen/BombermenServer.java b/bombermen2/bombermen-server/src/pt/up/fe/pt/lpoo/bombermen/BombermenServer.java index 3e349b7..8d20e23 100644 --- a/bombermen2/bombermen-server/src/pt/up/fe/pt/lpoo/bombermen/BombermenServer.java +++ b/bombermen2/bombermen-server/src/pt/up/fe/pt/lpoo/bombermen/BombermenServer.java @@ -1,391 +1,393 @@ package pt.up.fe.pt.lpoo.bombermen; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import pt.up.fe.pt.lpoo.bombermen.messages.CMSG_JOIN; import pt.up.fe.pt.lpoo.bombermen.messages.CMSG_MOVE; import pt.up.fe.pt.lpoo.bombermen.messages.CMSG_PLACE_BOMB; import pt.up.fe.pt.lpoo.bombermen.messages.Message; import pt.up.fe.pt.lpoo.bombermen.messages.SMSG_DESTROY; import pt.up.fe.pt.lpoo.bombermen.messages.SMSG_SPAWN; import pt.up.fe.pt.lpoo.utils.Ref; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; public class BombermenServer implements Runnable { private ServerSocket _socket = null; private int _lastId = 0; private HashMap<Integer, ClientHandler> _clients = new HashMap<Integer, ClientHandler>(); private HashMap<Integer, Entity> _entities = new HashMap<Integer, Entity>(); private int _numberOfClients = 0; private MessageHandler _messageHandler; private ArrayList<Entity> _entitiesToAdd = new ArrayList<Entity>(); private HashSet<Integer> _entitiesToRemove = new HashSet<Integer>(); private Queue<ClientMessage> _messageQueue = new LinkedList<ClientMessage>(); public HashMap<Integer, Entity> GetEntities() { return _entities; } public void RemoveEntityNextUpdate(int guid) { _entitiesToRemove.add(guid); } public void CreateEntityNextUpdate(Entity e) { _entitiesToAdd.add(e); } public int IncLastId() // returns previous id { return _lastId++; } public void PushMessage(int guid, Message msg) { _messageQueue.add(new ClientMessage(guid, msg)); } public void Update(int diff) { synchronized (_messageQueue) { while (!_messageQueue.isEmpty()) { _messageHandler.HandleMessage(_messageQueue.poll()); } } synchronized (_entities) { for (Entity e : _entities.values()) e.Update(diff); for (Entity e : _entitiesToAdd) _entities.put(e.GetGuid(), e); _entitiesToAdd.clear(); Iterator<Entity> it = _entities.values().iterator(); while (it.hasNext()) { int guid = it.next().GetGuid(); if (_entitiesToRemove.contains(guid)) { SendAll(new SMSG_DESTROY(guid)); it.remove(); } } _entitiesToRemove.clear(); for (Entity e1 : _entities.values()) for (Entity e2 : _entities.values()) if (e1.GetGuid() != e2.GetGuid()) if (e1.Collides(e2)) e1.OnCollision(e2); } synchronized (_clients) { ArrayList<Integer> removed = new ArrayList<Integer>(); Iterator<ClientHandler> it = _clients.values().iterator(); while (it.hasNext()) { ClientHandler ch = it.next(); ch.Update(diff); if (!ch.IsStillConnected()) { removed.add(ch.Guid); it.remove(); System.out.println("Client Removed."); } } for (Integer i : removed) { _entities.remove(i); SMSG_DESTROY msg = new SMSG_DESTROY(i); for (ClientHandler ch : _clients.values()) { ch.ClientSender.Send(msg); } } } if (_numberOfClients != _clients.size()) { _numberOfClients = _clients.size(); System.out.println("Number of Clients: " + _numberOfClients); } } public BombermenServer(int port) throws IOException { _socket = new ServerSocket(port); System.out.println("Server created - " + InetAddress.getLocalHost().getHostAddress() + ":" + _socket.getLocalPort()); _messageHandler = new MessageHandler() { @Override protected void CMSG_MOVE_Handler(int guid, CMSG_MOVE msg) { - Player p = _entities.get(guid).ToPlayer(); + Entity e = _entities.get(guid); + if (e == null) return; + Player p = e.ToPlayer(); if (p == null) return; p.SetMoving(msg.Val, msg.Dir); } @Override protected void CMSG_PLACE_BOMB_Handler(int guid, CMSG_PLACE_BOMB msg) { System.out.println("Place bomb message received from " + guid + " : " + msg); Player p = _entities.get(guid).ToPlayer(); if (p == null) { System.out.println("Player sent unknown guid (" + guid + "). Ignored."); return; } if (p.GetCurrentBombs() >= p.GetMaxBombs()) { System.out.println("Player tried to place bomb without max bombs available."); return; } p.UpdateCurrentBombs(1); float playerX = p.GetX(); float playerY = p.GetY(); int tileX = MathUtils.floor(playerX / Constants.CELL_SIZE); int tileY = MathUtils.floor(playerY / Constants.CELL_SIZE); float x = tileX * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; float y = tileY * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; Vector2 position = new Vector2(x, y); // (0.9, 0.9) Bomb b = new Bomb(BombermenServer.this.IncLastId(), p.GetGuid(), position, p.GetExplosionRadius(), BombermenServer.this); BombermenServer.this.CreateEntityNextUpdate(b); SMSG_SPAWN bombMsg = b.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) ch.ClientSender.Send(bombMsg); } @Override protected void Default_Handler(int guid, Message msg) { System.out.println("Unhandled message received from " + guid + " : " + msg); } @Override protected void CMSG_JOIN_Handler(int guid, CMSG_JOIN msg) { Player p = new Player(guid, msg.Name, new Vector2(40, 40), BombermenServer.this); _entities.put(guid, p); System.out.println("Player '" + msg.Name + "' (guid: " + guid + ") just joined."); SMSG_SPAWN msg1 = p.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) if (ch.Guid != guid) ch.ClientSender.Send(msg1); ClientHandler ch = _clients.get(guid); for (Entity e : _entities.values()) ch.ClientSender.Send(e.GetSpawnMessage()); } }; MapLoader builder = new MapLoader(this); Ref<Integer> width = new Ref<Integer>(0); Ref<Integer> height = new Ref<Integer>(0); if (!builder.TryLoad(0, width, height)) { System.out.println("Could not load map " + 0); return; } new Thread(this).start(); } public static void main(String[] args) throws IOException { BombermenServer sv = new BombermenServer(7777); long millis = System.currentTimeMillis(); while (true) { int dt = (int) (System.currentTimeMillis() - millis); millis = System.currentTimeMillis(); sv.Update(dt); try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } } @Override public void run() { do { Socket socket; try { socket = _socket.accept(); int clientId = IncLastId(); ClientHandler ch; ch = new ClientHandler(clientId, socket, this); synchronized (_clients) { _clients.put(clientId, ch); } } catch (IOException e) { e.printStackTrace(); } } while (true); } public void SendAll(Message msg) { for (ClientHandler ch : _clients.values()) ch.ClientSender.Send(msg); } } class ClientHandler { public final int Guid; private Socket _socket; private final BombermenServer _server; private boolean _stillConnected = true; private int _timer = 0; public final Sender<Message> ClientSender; public class ServerReceiver extends Receiver<Message> { public ServerReceiver(Socket socket) { super(socket); } @Override public void run() { try { ObjectInputStream in = new ObjectInputStream(_socket.getInputStream()); while (!_done) { try { Message msg = (Message) in.readObject(); if (_done) break; if (msg == null) continue; _server.PushMessage(Guid, msg); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (EOFException e) { } } in.close(); } catch (SocketException e) { } catch (IOException e1) { e1.printStackTrace(); } } }; public final Receiver<Message> ClientReceiver; public ClientHandler(int guid, Socket socket, BombermenServer server) { Guid = guid; _socket = socket; _server = server; ClientSender = new Sender<Message>(_socket); ClientReceiver = new ServerReceiver(_socket); } public boolean IsStillConnected() { return _stillConnected; } public void Update(int diff) { _timer += diff; if (_timer >= 1000) { _timer = 0; try { ClientSender.TrySend(null); _stillConnected = true; } catch (IOException e) { _stillConnected = false; } } } }
true
true
public BombermenServer(int port) throws IOException { _socket = new ServerSocket(port); System.out.println("Server created - " + InetAddress.getLocalHost().getHostAddress() + ":" + _socket.getLocalPort()); _messageHandler = new MessageHandler() { @Override protected void CMSG_MOVE_Handler(int guid, CMSG_MOVE msg) { Player p = _entities.get(guid).ToPlayer(); if (p == null) return; p.SetMoving(msg.Val, msg.Dir); } @Override protected void CMSG_PLACE_BOMB_Handler(int guid, CMSG_PLACE_BOMB msg) { System.out.println("Place bomb message received from " + guid + " : " + msg); Player p = _entities.get(guid).ToPlayer(); if (p == null) { System.out.println("Player sent unknown guid (" + guid + "). Ignored."); return; } if (p.GetCurrentBombs() >= p.GetMaxBombs()) { System.out.println("Player tried to place bomb without max bombs available."); return; } p.UpdateCurrentBombs(1); float playerX = p.GetX(); float playerY = p.GetY(); int tileX = MathUtils.floor(playerX / Constants.CELL_SIZE); int tileY = MathUtils.floor(playerY / Constants.CELL_SIZE); float x = tileX * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; float y = tileY * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; Vector2 position = new Vector2(x, y); // (0.9, 0.9) Bomb b = new Bomb(BombermenServer.this.IncLastId(), p.GetGuid(), position, p.GetExplosionRadius(), BombermenServer.this); BombermenServer.this.CreateEntityNextUpdate(b); SMSG_SPAWN bombMsg = b.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) ch.ClientSender.Send(bombMsg); } @Override protected void Default_Handler(int guid, Message msg) { System.out.println("Unhandled message received from " + guid + " : " + msg); } @Override protected void CMSG_JOIN_Handler(int guid, CMSG_JOIN msg) { Player p = new Player(guid, msg.Name, new Vector2(40, 40), BombermenServer.this); _entities.put(guid, p); System.out.println("Player '" + msg.Name + "' (guid: " + guid + ") just joined."); SMSG_SPAWN msg1 = p.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) if (ch.Guid != guid) ch.ClientSender.Send(msg1); ClientHandler ch = _clients.get(guid); for (Entity e : _entities.values()) ch.ClientSender.Send(e.GetSpawnMessage()); } }; MapLoader builder = new MapLoader(this); Ref<Integer> width = new Ref<Integer>(0); Ref<Integer> height = new Ref<Integer>(0); if (!builder.TryLoad(0, width, height)) { System.out.println("Could not load map " + 0); return; } new Thread(this).start(); }
public BombermenServer(int port) throws IOException { _socket = new ServerSocket(port); System.out.println("Server created - " + InetAddress.getLocalHost().getHostAddress() + ":" + _socket.getLocalPort()); _messageHandler = new MessageHandler() { @Override protected void CMSG_MOVE_Handler(int guid, CMSG_MOVE msg) { Entity e = _entities.get(guid); if (e == null) return; Player p = e.ToPlayer(); if (p == null) return; p.SetMoving(msg.Val, msg.Dir); } @Override protected void CMSG_PLACE_BOMB_Handler(int guid, CMSG_PLACE_BOMB msg) { System.out.println("Place bomb message received from " + guid + " : " + msg); Player p = _entities.get(guid).ToPlayer(); if (p == null) { System.out.println("Player sent unknown guid (" + guid + "). Ignored."); return; } if (p.GetCurrentBombs() >= p.GetMaxBombs()) { System.out.println("Player tried to place bomb without max bombs available."); return; } p.UpdateCurrentBombs(1); float playerX = p.GetX(); float playerY = p.GetY(); int tileX = MathUtils.floor(playerX / Constants.CELL_SIZE); int tileY = MathUtils.floor(playerY / Constants.CELL_SIZE); float x = tileX * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; float y = tileY * Constants.CELL_SIZE + 0.1f * Constants.CELL_SIZE; Vector2 position = new Vector2(x, y); // (0.9, 0.9) Bomb b = new Bomb(BombermenServer.this.IncLastId(), p.GetGuid(), position, p.GetExplosionRadius(), BombermenServer.this); BombermenServer.this.CreateEntityNextUpdate(b); SMSG_SPAWN bombMsg = b.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) ch.ClientSender.Send(bombMsg); } @Override protected void Default_Handler(int guid, Message msg) { System.out.println("Unhandled message received from " + guid + " : " + msg); } @Override protected void CMSG_JOIN_Handler(int guid, CMSG_JOIN msg) { Player p = new Player(guid, msg.Name, new Vector2(40, 40), BombermenServer.this); _entities.put(guid, p); System.out.println("Player '" + msg.Name + "' (guid: " + guid + ") just joined."); SMSG_SPAWN msg1 = p.GetSpawnMessage(); for (ClientHandler ch : _clients.values()) if (ch.Guid != guid) ch.ClientSender.Send(msg1); ClientHandler ch = _clients.get(guid); for (Entity e : _entities.values()) ch.ClientSender.Send(e.GetSpawnMessage()); } }; MapLoader builder = new MapLoader(this); Ref<Integer> width = new Ref<Integer>(0); Ref<Integer> height = new Ref<Integer>(0); if (!builder.TryLoad(0, width, height)) { System.out.println("Could not load map " + 0); return; } new Thread(this).start(); }
diff --git a/FatTnt/src/me/asofold/bukkit/fattnt/effects/ExplosionManager.java b/FatTnt/src/me/asofold/bukkit/fattnt/effects/ExplosionManager.java index abec76b..ed9e1a9 100644 --- a/FatTnt/src/me/asofold/bukkit/fattnt/effects/ExplosionManager.java +++ b/FatTnt/src/me/asofold/bukkit/fattnt/effects/ExplosionManager.java @@ -1,240 +1,240 @@ package me.asofold.bukkit.fattnt.effects; import java.util.Collection; import java.util.List; import java.util.Random; import me.asofold.bukkit.fattnt.FatTnt; import me.asofold.bukkit.fattnt.config.Defaults; import me.asofold.bukkit.fattnt.config.Settings; import me.asofold.bukkit.fattnt.events.FatEntityDamageEvent; import me.asofold.bukkit.fattnt.events.FatEntityExplodeEvent; import me.asofold.bukkit.fattnt.propagation.Propagation; import me.asofold.bukkit.fattnt.stats.Stats; import me.asofold.bukkit.fattnt.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.craftbukkit.entity.CraftTNTPrimed; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginManager; import org.bukkit.util.Vector; /** * Static method utility ( currently). * @author mc_dev * */ public class ExplosionManager { public static final Random random = new Random(System.currentTimeMillis()-1256875); private static Stats stats = null; /** * This does not create the explosion effect ! * @param world * @param x * @param y * @param z * @param realRadius * @param fire * @param explEntity * @param entityType * @param nearbyEntities can be null * @param settings * @param propagation */ public static void applyExplosionEffects(World world, double x, double y, double z, float realRadius, boolean fire, Entity explEntity, EntityType entityType, List<Entity> nearbyEntities, float damageMultiplier, Settings settings, Propagation propagation) { if ( realRadius > settings.maxRadius){ // TODO: settings ? realRadius = settings.maxRadius; } else if (realRadius == 0.0f) return; PluginManager pm = Bukkit.getPluginManager(); // blocks: long ms = System.nanoTime(); List<Block> affected = propagation.getExplodingBlocks(world , x, y, z, realRadius); stats.addStats(FatTnt.statsGetBlocks, System.nanoTime()-ms); stats.addStats(FatTnt.statsBlocksCollected, affected.size()); stats.addStats(FatTnt.statsStrength, (long) realRadius); FatExplosionSpecs specs = new FatExplosionSpecs(); EntityExplodeEvent exE = new FatEntityExplodeEvent(explEntity, new Location(world,x,y,z), affected, settings.defaultYield , specs); pm.callEvent(exE); if (exE.isCancelled()) return; // block effects: ms = System.nanoTime(); applyBlockEffects(world, x, y, z, realRadius, exE.blockList(), exE.getYield(), settings, propagation, specs); stats.addStats(FatTnt.statsApplyBlocks, System.nanoTime()-ms); // entities: if ( nearbyEntities != null){ ms = System.nanoTime(); applyEntityEffects(world, x, y, z, realRadius, nearbyEntities, damageMultiplier, settings, propagation, specs); stats.addStats(FatTnt.statsApplyEntities, System.nanoTime()-ms); } } /** * Block manuipulations for explosions. * @param world * @param x * @param y * @param z * @param realRadius * @param blocks * @param defaultYield * @param settings * @param propagation * @param specs */ public static void applyBlockEffects(World world, double x, double y, double z, float realRadius, List<Block> blocks, float defaultYield, Settings settings, Propagation propagation, FatExplosionSpecs specs){ // final List<block> directExplode = new LinkedList<block>(); // if set in config. - maybe later (split method to avoid recursion !) for ( Block block : blocks){ if (block.getType() == Material.TNT){ block.setTypeId(0, true); Location loc = block.getLocation().add(Defaults.vCenter); final float effRad = propagation.getStrength(loc); // effective strength/radius // if ( effRad > thresholdTntDirect){ // directExplode.add(block); // continue; // } // do spawn tnt-primed try{ Entity entity = world.spawn(loc, CraftTNTPrimed.class); if (entity == null) continue; if ( !(entity instanceof TNTPrimed)) continue; if ( effRad == 0.0f) continue; // not affected if (settings.velOnPrime) addRandomVelocity(entity, loc, x,y,z, effRad, realRadius, settings); } catch( Throwable t){ // maybe later log } continue; } // All other blocks: Collection<ItemStack> drops = block.getDrops(); for (ItemStack drop : drops){ if ( random.nextFloat()<=defaultYield){ Location loc = block.getLocation().add(Defaults.vCenter); Item item = world.dropItemNaturally(loc, drop.clone()); if (item==null) continue; //addRandomVelocity(item, loc, x,y,z, realRadius); } } block.setTypeId(0, true); // TODO: evaluate if still spazzing appears (if so: use false, and then iterate again for applying physics after block changes). } } /** * Entity manipulations for explosions. * @param world * @param x * @param y * @param z * @param realRadius * @param nearbyEntities * @param damageMultiplier * @param settings * @param propagation * @param specs */ public static void applyEntityEffects(World world, double x, double y, double z, float realRadius, List<Entity> nearbyEntities, float damageMultiplier, Settings settings, Propagation propagation, FatExplosionSpecs specs) { if ( realRadius > settings.maxRadius){ // TODO: settings ? realRadius = settings.maxRadius; } else if (realRadius == 0.0f) return; PluginManager pm = Bukkit.getPluginManager(); // entities: for ( Entity entity : nearbyEntities){ // test damage: final Location loc = entity.getLocation(); final float effRad = propagation.getStrength(loc); // effective strength/radius if ( effRad == 0.0f) continue; // not affected boolean addVelocity = true; boolean useDamage = true; if (settings.sparePrimed && (entity instanceof TNTPrimed)){ - addVelocity = false; + addVelocity = true; useDamage = false; } if (useDamage){ // TODO: damage entities according to type int damage = 1 + (int) (effRad*settings.damageMultiplier*damageMultiplier) ; // TODO: take into account armor, enchantments and such? EntityDamageEvent event = new FatEntityDamageEvent(entity, DamageCause.ENTITY_EXPLOSION, damage, specs); pm.callEvent(event); if (!event.isCancelled()){ if (Utils.damageEntity(event) > 0){ // (declined: consider using "effective damage" for stats.) // (but:) Only include >0 damage (that might lose some armored players later, but prevents including invalid entities. stats.addStats(FatTnt.statsDamage, damage); } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } if (addVelocity) addRandomVelocity(entity, loc, x,y,z, effRad, realRadius, settings); } } /** * Add velocity according to settings * @param entity * @param loc * @param x * @param y * @param z * @param part part of radius (effective), as with FatTnt.getExplosionStrength * @param max max radius */ public static void addRandomVelocity(Entity entity, Location loc, double x, double y, double z, float part, float max, Settings settings) { // TODO: make some things configurable, possible entity dependent and ! if (!settings.velUse) return; Vector v = entity.getVelocity(); Vector fromCenter = new Vector(loc.getX()-x,loc.getY()-y,loc.getZ()-z).normalize(); Vector rv = v.add((fromCenter.multiply(settings.velMin+random.nextFloat()*settings.velCen)).add(Vector.getRandom().multiply(settings.velRan)).multiply(part/max)); if (entity instanceof LivingEntity) ((LivingEntity) entity).setVelocity(rv); else if (entity instanceof TNTPrimed) ((TNTPrimed) entity).setVelocity(rv); else entity.setVelocity(rv); } /** * Apply the explosion effect in that world, * currently this simply delegates to create an explosion with radius 0, * later it might add other effects. * @param world * @param x * @param y * @param z * @param radius * @param fire */ public static void createExplosionEffect(World world, double x, double y, double z, float radius, boolean fire) { world.createExplosion(new Location(world,x,y,z), 0.0F); } public static void setStats(Stats stats){ ExplosionManager.stats = stats; } }
true
true
public static void applyEntityEffects(World world, double x, double y, double z, float realRadius, List<Entity> nearbyEntities, float damageMultiplier, Settings settings, Propagation propagation, FatExplosionSpecs specs) { if ( realRadius > settings.maxRadius){ // TODO: settings ? realRadius = settings.maxRadius; } else if (realRadius == 0.0f) return; PluginManager pm = Bukkit.getPluginManager(); // entities: for ( Entity entity : nearbyEntities){ // test damage: final Location loc = entity.getLocation(); final float effRad = propagation.getStrength(loc); // effective strength/radius if ( effRad == 0.0f) continue; // not affected boolean addVelocity = true; boolean useDamage = true; if (settings.sparePrimed && (entity instanceof TNTPrimed)){ addVelocity = false; useDamage = false; } if (useDamage){ // TODO: damage entities according to type int damage = 1 + (int) (effRad*settings.damageMultiplier*damageMultiplier) ; // TODO: take into account armor, enchantments and such? EntityDamageEvent event = new FatEntityDamageEvent(entity, DamageCause.ENTITY_EXPLOSION, damage, specs); pm.callEvent(event); if (!event.isCancelled()){ if (Utils.damageEntity(event) > 0){ // (declined: consider using "effective damage" for stats.) // (but:) Only include >0 damage (that might lose some armored players later, but prevents including invalid entities. stats.addStats(FatTnt.statsDamage, damage); } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } if (addVelocity) addRandomVelocity(entity, loc, x,y,z, effRad, realRadius, settings); } }
public static void applyEntityEffects(World world, double x, double y, double z, float realRadius, List<Entity> nearbyEntities, float damageMultiplier, Settings settings, Propagation propagation, FatExplosionSpecs specs) { if ( realRadius > settings.maxRadius){ // TODO: settings ? realRadius = settings.maxRadius; } else if (realRadius == 0.0f) return; PluginManager pm = Bukkit.getPluginManager(); // entities: for ( Entity entity : nearbyEntities){ // test damage: final Location loc = entity.getLocation(); final float effRad = propagation.getStrength(loc); // effective strength/radius if ( effRad == 0.0f) continue; // not affected boolean addVelocity = true; boolean useDamage = true; if (settings.sparePrimed && (entity instanceof TNTPrimed)){ addVelocity = true; useDamage = false; } if (useDamage){ // TODO: damage entities according to type int damage = 1 + (int) (effRad*settings.damageMultiplier*damageMultiplier) ; // TODO: take into account armor, enchantments and such? EntityDamageEvent event = new FatEntityDamageEvent(entity, DamageCause.ENTITY_EXPLOSION, damage, specs); pm.callEvent(event); if (!event.isCancelled()){ if (Utils.damageEntity(event) > 0){ // (declined: consider using "effective damage" for stats.) // (but:) Only include >0 damage (that might lose some armored players later, but prevents including invalid entities. stats.addStats(FatTnt.statsDamage, damage); } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } } else{ // CURRENTLY, MIGHT BE CHANGED addVelocity = false; } if (addVelocity) addRandomVelocity(entity, loc, x,y,z, effRad, realRadius, settings); } }
diff --git a/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java b/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java index e24cc2e4..67fe3b9e 100644 --- a/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java +++ b/src/org/intellij/erlang/formatter/ErlangFormattingModelBuilder.java @@ -1,112 +1,113 @@ /* * Copyright 2012 Sergey Ignatov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.erlang.formatter; import com.intellij.formatting.*; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.tree.TokenSet; import org.intellij.erlang.ErlangLanguage; import org.jetbrains.annotations.NotNull; import static org.intellij.erlang.ErlangTypes.*; /** * @author ignatov */ public class ErlangFormattingModelBuilder implements FormattingModelBuilder { @NotNull @Override public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) { CommonCodeStyleSettings erlangSettings = settings.getCommonSettings(ErlangLanguage.INSTANCE); final ErlangBlock block = new ErlangBlock(element.getNode(), null, null, erlangSettings, createSpacingBuilder(erlangSettings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); } private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) { TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE); return new SpacingBuilder(settings.getRootSettings()) .before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA) .after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA) // .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1) // .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none() // .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none() .around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .after(ERL_BRACKET_LEFT).none() .before(ERL_BRACKET_RIGHT).none() .after(ERL_CURLY_LEFT).none() .before(ERL_CURLY_RIGHT).none() .after(ERL_BIN_START).none() .before(ERL_BIN_END).none() .before(ERL_ARGUMENT_DEFINITION_LIST).none() .before(ERL_ARGUMENT_LIST).none() .withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES) .withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true) .withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true) .withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true) .beforeInside(rules, ERL_PAR_LEFT).none() .aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none() .aroundInside(ERL_DOT, ERL_RECORD_EXPRESSION).none() .aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none() .before(ERL_DOT).none() .around(ERL_QMARK).none() .before(ERL_RECORD_TUPLE).none() + .before(ERL_END).spaces(1) ; } @Override public TextRange getRangeAffectingIndent(PsiFile psiFile, int i, ASTNode astNode) { return null; } }
true
true
private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) { TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE); return new SpacingBuilder(settings.getRootSettings()) .before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA) .after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA) // .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1) // .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none() // .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none() .around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .after(ERL_BRACKET_LEFT).none() .before(ERL_BRACKET_RIGHT).none() .after(ERL_CURLY_LEFT).none() .before(ERL_CURLY_RIGHT).none() .after(ERL_BIN_START).none() .before(ERL_BIN_END).none() .before(ERL_ARGUMENT_DEFINITION_LIST).none() .before(ERL_ARGUMENT_LIST).none() .withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES) .withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true) .withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true) .withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true) .beforeInside(rules, ERL_PAR_LEFT).none() .aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none() .aroundInside(ERL_DOT, ERL_RECORD_EXPRESSION).none() .aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none() .before(ERL_DOT).none() .around(ERL_QMARK).none() .before(ERL_RECORD_TUPLE).none() ; }
private static SpacingBuilder createSpacingBuilder(CommonCodeStyleSettings settings) { TokenSet rules = TokenSet.create(ERL_RULE, ERL_RECORD_DEFINITION, ERL_INCLUDE, ERL_MACROS_DEFINITION, ERL_ATTRIBUTE); return new SpacingBuilder(settings.getRootSettings()) .before(ERL_COMMA).spaceIf(settings.SPACE_BEFORE_COMMA) .after(ERL_COMMA).spaceIf(settings.SPACE_AFTER_COMMA) // .betweenInside(ERL_OP_EQ, ERL_BINARY_EXPRESSION, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_BINARY_TYPE, ERL_RECORD_FIELD).spaces(1) // .betweenInside(ERL_OP_EQ, ERL_LIST_COMPREHENSION, ERL_RECORD_FIELD).spaces(1) // .aroundInside(ERL_OP_EQ, ERL_RECORD_FIELD).none() // .aroundInside(ERL_OP_EQ, ERL_TYPED_EXPR).none() .around(ERL_OP_EQ).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_LT_MINUS).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_EXL).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .after(ERL_ARROW).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .before(ERL_CLAUSE_BODY).spaceIf(settings.SPACE_AROUND_ASSIGNMENT_OPERATORS) .around(ERL_OP_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .around(ERL_OP_PLUS_PLUS).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_MINUS, ERL_ADDITIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_ADDITIVE_OPERATORS) .aroundInside(ERL_OP_AR_DIV, ERL_MULTIPLICATIVE_EXPRESSION).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_AR_MUL).spaceIf(settings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS) .around(ERL_OP_EQ_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_DIV_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_EQ_COL_EQ).spaceIf(settings.SPACE_AROUND_EQUALITY_OPERATORS) .around(ERL_OP_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_EQ_LT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OP_GT_EQ).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .around(ERL_OR).spaceIf(settings.SPACE_AROUND_LOGICAL_OPERATORS) .after(ERL_BRACKET_LEFT).none() .before(ERL_BRACKET_RIGHT).none() .after(ERL_CURLY_LEFT).none() .before(ERL_CURLY_RIGHT).none() .after(ERL_BIN_START).none() .before(ERL_BIN_END).none() .before(ERL_ARGUMENT_DEFINITION_LIST).none() .before(ERL_ARGUMENT_LIST).none() .withinPair(ERL_PAR_LEFT, ERL_PAR_RIGHT).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES) .withinPair(ERL_BRACKET_LEFT, ERL_BRACKET_RIGHT).spaceIf(true) .withinPair(ERL_CURLY_LEFT, ERL_CURLY_RIGHT).spaceIf(true) .withinPair(ERL_BIN_START, ERL_BIN_END).spaceIf(true) .beforeInside(rules, ERL_PAR_LEFT).none() .aroundInside(ERL_COLON, ERL_GLOBAL_FUNCTION_CALL_EXPRESSION).none() .aroundInside(ERL_DOT, ERL_RECORD_EXPRESSION).none() .aroundInside(ERL_RADIX, ERL_RECORD_EXPRESSION).none() .before(ERL_DOT).none() .around(ERL_QMARK).none() .before(ERL_RECORD_TUPLE).none() .before(ERL_END).spaces(1) ; }
diff --git a/util-api/api/src/java/org/sakaiproject/javax/SearchFilter.java b/util-api/api/src/java/org/sakaiproject/javax/SearchFilter.java index e410fe9..2664427 100644 --- a/util-api/api/src/java/org/sakaiproject/javax/SearchFilter.java +++ b/util-api/api/src/java/org/sakaiproject/javax/SearchFilter.java @@ -1,46 +1,46 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.javax; /** * <p> * SearchFilter is a paricular kind of Filter where the code using the filter * may choose do something other than retrieve all the objects sequentally and * present them for acceptance. When code is using a SearchFilter the * code may decide to consult a search index to more efficiently retrieve * results. This also might result in objects returned by relevance * order. SearchFilter objects must implement the accept() method * because the calling code may or may not know how to peer inside * the particular objects being searched. If the calling code * has no optimisation for search it may revert to an approach of retrieving * all items and presenting them to the accept() method of a SearchFilter. * </p> */ public interface SearchFilter extends Filter { /** * Returns the search string for this filter. * * @return the search string for this filter. */ - boolean getSearchString(); + String getSearchString(); }
true
true
boolean getSearchString();
String getSearchString();
diff --git a/src/web/org/openmrs/web/controller/OptionsFormController.java b/src/web/org/openmrs/web/controller/OptionsFormController.java index 6e12a6a8..9b27ce55 100644 --- a/src/web/org/openmrs/web/controller/OptionsFormController.java +++ b/src/web/org/openmrs/web/controller/OptionsFormController.java @@ -1,302 +1,303 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.web.controller; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.PersonName; import org.openmrs.User; import org.openmrs.api.APIException; import org.openmrs.api.LocationService; import org.openmrs.api.PasswordException; import org.openmrs.api.UserService; import org.openmrs.api.context.Context; import org.openmrs.util.OpenmrsConstants; import org.openmrs.util.OpenmrsUtil; import org.openmrs.web.OptionsForm; import org.openmrs.web.WebConstants; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; /** * This is the controller for the "My Profile" page. This lets logged in users set personal * preferences, update their own information, etc. * * @see OptionsForm */ public class OptionsFormController extends SimpleFormController { /** Logger for this class and subclasses */ protected final Log log = LogFactory.getLog(getClass()); /** * @see org.springframework.web.servlet.mvc.AbstractFormController#processFormSubmission(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws Exception { OptionsForm opts = (OptionsForm) object; if (opts.getUsername().length() > 0) { if (opts.getUsername().length() < 3) { errors.rejectValue("username", "error.username.weak"); } if (opts.getUsername().charAt(0) < 'A' || opts.getUsername().charAt(0) > 'z') { errors.rejectValue("username", "error.username.invalid"); } } if (opts.getUsername().length() > 0) if (!opts.getOldPassword().equals("")) { if (opts.getNewPassword().equals("")) errors.rejectValue("newPassword", "error.password.weak"); else if (!opts.getNewPassword().equals(opts.getConfirmPassword())) { errors.rejectValue("newPassword", "error.password.match"); errors.rejectValue("confirmPassword", "error.password.match"); } } if (!opts.getSecretQuestionPassword().equals("")) { if (!opts.getSecretAnswerConfirm().equals(opts.getSecretAnswerNew())) { errors.rejectValue("secretAnswerNew", "error.options.secretAnswer.match"); errors.rejectValue("secretAnswerConfirm", "error.options.secretAnswer.match"); } } return super.processFormSubmission(request, response, object, errors); } /** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (!errors.hasErrors()) { User loginUser = Context.getAuthenticatedUser(); UserService us = Context.getUserService(); User user = null; try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); user = us.getUser(loginUser.getUserId()); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } OptionsForm opts = (OptionsForm) obj; Map<String, String> properties = user.getUserProperties(); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation()); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, opts.getDefaultLocale()); properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, opts.getProficientLocales()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION, opts.getNotification() == null ? "" : opts .getNotification().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS, opts.getNotificationAddress().toString()); if (!opts.getOldPassword().equals("")) { try { String password = opts.getNewPassword(); //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId())); } catch (PasswordException e) { errors.reject(e.getMessage()); } if (password.equals(opts.getOldPassword()) && !errors.hasErrors()) errors.reject("error.password.different"); } if (!errors.hasErrors()) { us.changePassword(opts.getOldPassword(), password); + opts.setSecretQuestionPassword(password); if (properties.containsKey(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD)) properties.remove(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD); } } catch (APIException e) { errors.rejectValue("oldPassword", "error.password.match"); } } else { // if they left the old password blank but filled in new password if (!opts.getNewPassword().equals("")) { errors.rejectValue("oldPassword", "error.password.incorrect"); } } if (!opts.getSecretQuestionPassword().equals("")) { if (!errors.hasErrors()) { try { user.setSecretQuestion(opts.getSecretQuestionNew()); us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(), opts .getSecretAnswerNew()); } catch (APIException e) { errors.rejectValue("secretQuestionPassword", "error.password.match"); } } } else if (!opts.getSecretAnswerNew().equals("")) { // if they left the old password blank but filled in new password errors.rejectValue("secretQuestionPassword", "error.password.incorrect"); } if (opts.getUsername().length() > 0 && !errors.hasErrors()) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); if (us.hasDuplicateUsername(user)) { errors.rejectValue("username", "error.username.taken"); } } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } } if (!errors.hasErrors()) { user.setUsername(opts.getUsername()); user.setUserProperties(properties); // new name PersonName newPersonName = opts.getPersonName(); // existing name PersonName existingPersonName = user.getPersonName(); // if two are not equal then make the new one the preferred, make the old one voided if (!existingPersonName.equalsContent(newPersonName)) { existingPersonName.setPreferred(false); existingPersonName.setVoided(true); existingPersonName.setVoidedBy(user); existingPersonName.setDateVoided(new Date()); existingPersonName.setVoidReason("Changed name on own options form"); newPersonName.setPreferred(true); user.addName(newPersonName); } try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); us.saveUser(user, null); // update login user object so that the new name is visible in the webapp Context.refreshAuthenticatedUser(); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved"); } else { return super.processFormSubmission(request, response, opts, errors); } view = getSuccessView(); } return new ModelAndView(new RedirectView(view)); } /** * This is called prior to displaying a form for the first time. It tells Spring the * form/command object to load into the request * * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest) */ protected Object formBackingObject(HttpServletRequest request) throws ServletException { OptionsForm opts = new OptionsForm(); if (Context.isAuthenticated()) { User user = Context.getAuthenticatedUser(); Map<String, String> props = user.getUserProperties(); opts.setDefaultLocation(props.get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION)); opts.setDefaultLocale(props.get(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE)); opts.setProficientLocales(props.get(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES)); opts.setShowRetiredMessage(new Boolean(props.get(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED))); opts.setVerbose(new Boolean(props.get(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE))); opts.setUsername(user.getUsername()); opts.setSecretQuestionNew(user.getSecretQuestion()); // Get a copy of the current person name and clear the id so that they are separate objects PersonName personName = PersonName.newInstance(user.getPersonName()); personName.setPersonNameId(null); opts.setPersonName(personName); opts.setNotification(props.get(OpenmrsConstants.USER_PROPERTY_NOTIFICATION)); opts.setNotificationAddress(props.get(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS)); } return opts; } /** * Called prior to form display. Allows for data to be put in the request to be used in the view * * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest) */ protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception { HttpSession httpSession = request.getSession(); Map<String, Object> map = new HashMap<String, Object>(); if (Context.isAuthenticated()) { LocationService ls = Context.getLocationService(); // set location options map.put("locations", ls.getAllLocations()); // set language/locale options map.put("languages", Context.getAdministrationService().getPresentationLocales()); String resetPassword = (String) httpSession.getAttribute("resetPassword"); if (resetPassword == null) resetPassword = ""; else httpSession.removeAttribute("resetPassword"); map.put("resetPassword", resetPassword); } return map; } }
true
true
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (!errors.hasErrors()) { User loginUser = Context.getAuthenticatedUser(); UserService us = Context.getUserService(); User user = null; try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); user = us.getUser(loginUser.getUserId()); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } OptionsForm opts = (OptionsForm) obj; Map<String, String> properties = user.getUserProperties(); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation()); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, opts.getDefaultLocale()); properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, opts.getProficientLocales()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION, opts.getNotification() == null ? "" : opts .getNotification().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS, opts.getNotificationAddress().toString()); if (!opts.getOldPassword().equals("")) { try { String password = opts.getNewPassword(); //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId())); } catch (PasswordException e) { errors.reject(e.getMessage()); } if (password.equals(opts.getOldPassword()) && !errors.hasErrors()) errors.reject("error.password.different"); } if (!errors.hasErrors()) { us.changePassword(opts.getOldPassword(), password); if (properties.containsKey(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD)) properties.remove(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD); } } catch (APIException e) { errors.rejectValue("oldPassword", "error.password.match"); } } else { // if they left the old password blank but filled in new password if (!opts.getNewPassword().equals("")) { errors.rejectValue("oldPassword", "error.password.incorrect"); } } if (!opts.getSecretQuestionPassword().equals("")) { if (!errors.hasErrors()) { try { user.setSecretQuestion(opts.getSecretQuestionNew()); us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(), opts .getSecretAnswerNew()); } catch (APIException e) { errors.rejectValue("secretQuestionPassword", "error.password.match"); } } } else if (!opts.getSecretAnswerNew().equals("")) { // if they left the old password blank but filled in new password errors.rejectValue("secretQuestionPassword", "error.password.incorrect"); } if (opts.getUsername().length() > 0 && !errors.hasErrors()) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); if (us.hasDuplicateUsername(user)) { errors.rejectValue("username", "error.username.taken"); } } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } } if (!errors.hasErrors()) { user.setUsername(opts.getUsername()); user.setUserProperties(properties); // new name PersonName newPersonName = opts.getPersonName(); // existing name PersonName existingPersonName = user.getPersonName(); // if two are not equal then make the new one the preferred, make the old one voided if (!existingPersonName.equalsContent(newPersonName)) { existingPersonName.setPreferred(false); existingPersonName.setVoided(true); existingPersonName.setVoidedBy(user); existingPersonName.setDateVoided(new Date()); existingPersonName.setVoidReason("Changed name on own options form"); newPersonName.setPreferred(true); user.addName(newPersonName); } try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); us.saveUser(user, null); // update login user object so that the new name is visible in the webapp Context.refreshAuthenticatedUser(); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved"); } else { return super.processFormSubmission(request, response, opts, errors); } view = getSuccessView(); } return new ModelAndView(new RedirectView(view)); }
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { HttpSession httpSession = request.getSession(); String view = getFormView(); if (!errors.hasErrors()) { User loginUser = Context.getAuthenticatedUser(); UserService us = Context.getUserService(); User user = null; try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); user = us.getUser(loginUser.getUserId()); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } OptionsForm opts = (OptionsForm) obj; Map<String, String> properties = user.getUserProperties(); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation()); properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, opts.getDefaultLocale()); properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES, opts.getProficientLocales()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION, opts.getNotification() == null ? "" : opts .getNotification().toString()); properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS, opts.getNotificationAddress().toString()); if (!opts.getOldPassword().equals("")) { try { String password = opts.getNewPassword(); //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, String.valueOf(user.getUserId())); } catch (PasswordException e) { errors.reject(e.getMessage()); } if (password.equals(opts.getOldPassword()) && !errors.hasErrors()) errors.reject("error.password.different"); } if (!errors.hasErrors()) { us.changePassword(opts.getOldPassword(), password); opts.setSecretQuestionPassword(password); if (properties.containsKey(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD)) properties.remove(OpenmrsConstants.USER_PROPERTY_CHANGE_PASSWORD); } } catch (APIException e) { errors.rejectValue("oldPassword", "error.password.match"); } } else { // if they left the old password blank but filled in new password if (!opts.getNewPassword().equals("")) { errors.rejectValue("oldPassword", "error.password.incorrect"); } } if (!opts.getSecretQuestionPassword().equals("")) { if (!errors.hasErrors()) { try { user.setSecretQuestion(opts.getSecretQuestionNew()); us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(), opts .getSecretAnswerNew()); } catch (APIException e) { errors.rejectValue("secretQuestionPassword", "error.password.match"); } } } else if (!opts.getSecretAnswerNew().equals("")) { // if they left the old password blank but filled in new password errors.rejectValue("secretQuestionPassword", "error.password.incorrect"); } if (opts.getUsername().length() > 0 && !errors.hasErrors()) { try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); if (us.hasDuplicateUsername(user)) { errors.rejectValue("username", "error.username.taken"); } } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } } if (!errors.hasErrors()) { user.setUsername(opts.getUsername()); user.setUserProperties(properties); // new name PersonName newPersonName = opts.getPersonName(); // existing name PersonName existingPersonName = user.getPersonName(); // if two are not equal then make the new one the preferred, make the old one voided if (!existingPersonName.equalsContent(newPersonName)) { existingPersonName.setPreferred(false); existingPersonName.setVoided(true); existingPersonName.setVoidedBy(user); existingPersonName.setDateVoided(new Date()); existingPersonName.setVoidReason("Changed name on own options form"); newPersonName.setPreferred(true); user.addName(newPersonName); } try { Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); us.saveUser(user, null); // update login user object so that the new name is visible in the webapp Context.refreshAuthenticatedUser(); } finally { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved"); } else { return super.processFormSubmission(request, response, opts, errors); } view = getSuccessView(); } return new ModelAndView(new RedirectView(view)); }
diff --git a/src/test/java/rzhdpack/OpenRzd.java b/src/test/java/rzhdpack/OpenRzd.java index 86ba246..65ad4a9 100644 --- a/src/test/java/rzhdpack/OpenRzd.java +++ b/src/test/java/rzhdpack/OpenRzd.java @@ -1,33 +1,33 @@ package rzhdpack; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static org.testng.AssertJUnit.*; public class OpenRzd { private static WebDriver driver = new FirefoxDriver(); @Test public void openRzdRuAndVerifyItIsOpened() throws InterruptedException { driver.get("http://rzd.ru/"); List<WebElement> rzdLink = driver.findElements(By.xpath( "//a[@href='http://rzd.ru']")); - assertEquals("Link wasn't found", 0, rzdLink.size()); + assertEquals("Link wasn't found", 1, rzdLink.size()); } @AfterTest public void closeBrowser(){ driver.close(); } }
true
true
public void openRzdRuAndVerifyItIsOpened() throws InterruptedException { driver.get("http://rzd.ru/"); List<WebElement> rzdLink = driver.findElements(By.xpath( "//a[@href='http://rzd.ru']")); assertEquals("Link wasn't found", 0, rzdLink.size()); }
public void openRzdRuAndVerifyItIsOpened() throws InterruptedException { driver.get("http://rzd.ru/"); List<WebElement> rzdLink = driver.findElements(By.xpath( "//a[@href='http://rzd.ru']")); assertEquals("Link wasn't found", 1, rzdLink.size()); }
diff --git a/genetica-libraries/src/main/java/umcg/genetica/graphics/ViolinBoxPlot.java b/genetica-libraries/src/main/java/umcg/genetica/graphics/ViolinBoxPlot.java index 09aef037..12c40390 100644 --- a/genetica-libraries/src/main/java/umcg/genetica/graphics/ViolinBoxPlot.java +++ b/genetica-libraries/src/main/java/umcg/genetica/graphics/ViolinBoxPlot.java @@ -1,523 +1,523 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package umcg.genetica.graphics; import com.lowagie.text.DocumentException; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.GeneralPath; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import javax.imageio.ImageIO; import umcg.genetica.containers.Pair; import umcg.genetica.containers.Triple; import umcg.genetica.math.stats.WilcoxonMannWhitney; /** * * @author harmjan */ public class ViolinBoxPlot { public enum Output { PDF, PNG }; private double getWidth(String text, java.awt.Font font) { java.awt.Graphics2D g2d = (new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_ARGB)).createGraphics(); java.awt.font.TextLayout tL = new java.awt.font.TextLayout(text, font, g2d.getFontRenderContext()); return (double) tL.getBounds().getWidth(); } // draw multiple violinplots (for example for multiple datasets) format: vals[dataset][category][value] // xlabels format: xlabels2[dataset][category] public void draw(double[][][] vals, String[] datasetNames, String[][] xLabels2, Output output, String outputFileName) throws IOException { Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); // set up Graphics2D depending on required format using iText in case PDF Graphics2D g2d = null; com.lowagie.text.Document document = null; com.lowagie.text.pdf.PdfWriter writer = null; com.lowagie.text.pdf.PdfContentByte cb = null; BufferedImage bi = null; // draw individual box/violinplots java.awt.AlphaComposite alphaComposite25 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.25f); java.awt.AlphaComposite alphaComposite50 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.50f); java.awt.AlphaComposite alphaComposite100 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.00f); float fontSize = 12f; java.awt.Font font = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, (int) fontSize); java.awt.Font fontBold = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, (int) fontSize); java.awt.Font fontSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, 8); java.awt.Font fontBoldSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, 8); int[] datasetWitdths = new int[datasetNames.length]; int individualPlotWidth = 70; int individualPlotMarginLeft = 10; int individualPlotMarginRight = 10; int betweenDatasetMargin = 20; int marginLeft = 100; int marginRight = 100; int marginTop = 100; int marginBottom = 100; int innerHeight = 500; int totalDatasetWidth = 0; int tableElementHeight = 25; boolean printTable = false; int maxNrCategories = 0; for (int x = 0; x < datasetNames.length; x++) { int nrCategoriesInDataset = vals[x].length; datasetWitdths[x] = nrCategoriesInDataset * (individualPlotWidth + individualPlotMarginLeft + individualPlotMarginRight); if (nrCategoriesInDataset > 2) { printTable = true; if (nrCategoriesInDataset > maxNrCategories) { maxNrCategories = nrCategoriesInDataset; } } totalDatasetWidth += datasetWitdths[x]; } totalDatasetWidth += (datasetNames.length - 1) * betweenDatasetMargin; int docWidth = marginLeft + marginRight + totalDatasetWidth; int docHeight = marginTop + marginBottom + innerHeight; if (printTable) { docHeight += (maxNrCategories * tableElementHeight); } if (output == Output.PDF) { com.lowagie.text.Rectangle rectangle = new com.lowagie.text.Rectangle(docWidth, docHeight); document = new com.lowagie.text.Document(rectangle); try { writer = com.lowagie.text.pdf.PdfWriter.getInstance(document, new java.io.FileOutputStream(outputFileName)); } catch (DocumentException e) { throw new IOException(e.fillInStackTrace()); } document.open(); cb = writer.getDirectContent(); cb.saveState(); //com.lowagie.text.pdf.DefaultFontMapper fontMap = new com.lowagie.text.pdf.DefaultFontMapper(); g2d = cb.createGraphics(docWidth, docHeight); } else { bi = new BufferedImage(docWidth, docHeight, BufferedImage.TYPE_INT_RGB); g2d = bi.createGraphics(); } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.white); g2d.fillRect(0, 0, docWidth, docHeight); double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; - cern.jet.random.engine.RandomEngine randomEngine = new cern.jet.random.engine.DRand(); +// cern.jet.random.engine.RandomEngine randomEngine = new cern.jet.random.engine.DRand(); WilcoxonMannWhitney wmw = new WilcoxonMannWhitney(); double[][][] aucs = new double[vals.length][vals[0].length][vals[0].length]; double[][][] pvals = new double[vals.length][vals[0].length][vals[0].length]; for (int dataset = 0; dataset < datasetNames.length; dataset++) { double[][] valsForDs = vals[dataset]; // test between categories for (int category1 = 0; category1 < valsForDs.length; category1++) { double[] vals1 = valsForDs[category1]; double min1 = JSci.maths.ArrayMath.min(vals1); double max1 = JSci.maths.ArrayMath.max(vals1); if (min1 < minValue) { minValue = min1; } if (max1 > maxValue) { maxValue = max1; } for (int category2 = category1 + 1; category2 < valsForDs.length; category2++) { double[] vals2 = valsForDs[category2]; double pValueWilcoxon = wmw.returnWilcoxonMannWhitneyPValue(vals2, vals1); double auc = wmw.getAUC(); double min2 = JSci.maths.ArrayMath.min(vals2); double max2 = JSci.maths.ArrayMath.max(vals2); aucs[dataset][category1][category2] = auc; pvals[dataset][category1][category2] = pValueWilcoxon; if (max2 > maxValue) { maxValue = max2; } if (min2 < minValue) { minValue = min2; } } } } ArrayList<Pair<Double, Integer>> sortedPValuesPerDataset = new ArrayList<Pair<Double, Integer>>(); ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>> sortedPValuesPerCategory = new ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>>(); for (int dataset = 0; dataset < vals.length; dataset++) { // sort categories on the basis of their WMW results double[][] aucsfordataset = aucs[dataset]; double[][] pvaluesfordataset = pvals[dataset]; double minPvalueForDs = Double.MAX_VALUE; for (int category1 = 0; category1 < pvaluesfordataset.length; category1++) { for (int category2 = category1 + 1; category2 < pvaluesfordataset.length; category2++) { double valueToSort = pvaluesfordataset[category1][category2]; // if(sortByAUC){ // valueToSort = aucsfordataset[category1][category2]; // } sortedPValuesPerCategory.add(new Pair<Double, Triple<Integer, Integer, Integer>>(valueToSort, new Triple<Integer, Integer, Integer>(dataset, category1, category2), Pair.SORTBY.LEFT)); if (valueToSort < minPvalueForDs) { minPvalueForDs = valueToSort; } } } sortedPValuesPerDataset.add(new Pair<Double, Integer>(minPvalueForDs, dataset, Pair.SORTBY.LEFT)); } Collections.sort(sortedPValuesPerDataset, Collections.reverseOrder()); Collections.sort(sortedPValuesPerCategory, Collections.reverseOrder()); int datasetCounter = 0; int deltaX = 0; for (Pair<Double, Integer> pvalueDatasetPair : sortedPValuesPerDataset) { Integer datasetNumber = pvalueDatasetPair.getRight(); int datasetwidth = datasetWitdths[datasetNumber]; // draw the gradient g2d.setComposite(alphaComposite100); int x = marginLeft + deltaX; int height = innerHeight; java.awt.GradientPaint gradient = new java.awt.GradientPaint(0, marginTop, new Color(230, 230, 230), 0, height, new Color(250, 250, 250)); g2d.setPaint(gradient); g2d.fillRect(x - individualPlotMarginLeft / 2, marginTop - 90, datasetwidth, height + 100); // now get the sorted results per category within this dataset ArrayList<Triple<Integer, Integer, Integer>> sortedPValuesForDataset = new ArrayList<Triple<Integer, Integer, Integer>>(); for (Pair<Double, Triple<Integer, Integer, Integer>> pvalueTriplePair : sortedPValuesPerCategory) { System.out.println(pvalueTriplePair.toString()); if (pvalueTriplePair.getRight().getLeft().equals(datasetNumber)) { // this result belongs to this dataset sortedPValuesForDataset.add(pvalueTriplePair.getRight()); } } // reorder categories.. HashSet<Integer> visitedCategories = new HashSet<Integer>(); ArrayList<Integer> categoryOrder = new ArrayList<Integer>(); for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); if (!visitedCategories.contains(category1)) { categoryOrder.add(category1); visitedCategories.add(category1); } if (!visitedCategories.contains(category2)) { categoryOrder.add(category2); visitedCategories.add(category2); } } // print dataset name String datasetName = datasetNames[datasetNumber]; int y = marginTop; g2d.setColor(new Color(0, 0, 0)); g2d.setFont(fontBold); g2d.drawString(datasetName, x + 5, y - 70); g2d.setFont(font); // now we can plot the combinations between the categories (and their pvalues and aucs, yay!) int[] categoryIndex = new int[vals[datasetNumber].length]; int categoryCounter = 0; int plotStart = x + individualPlotMarginLeft; for (Integer category : categoryOrder) { double[] vals1 = vals[datasetNumber][category]; categoryIndex[category] = categoryCounter; // plot the individual box and violin plots g2d.setComposite(alphaComposite25); g2d.setColor(new Color(223, 36, 20)); int xposViolin = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * categoryCounter; int xposBoxPlot = xposViolin; // + (individualPlotWidth / 2 - 3) / 2; drawViolinPlot(g2d, xposViolin, y, individualPlotWidth, height, vals1, minValue, maxValue); g2d.setComposite(alphaComposite100); g2d.setColor(new Color(0, 0, 0)); drawBoxPlot(g2d, xposBoxPlot, y, individualPlotWidth, height, vals1, minValue, maxValue, false); // Draw bottom discrimator between candidate genes and other genes: double minVal1 = JSci.maths.ArrayMath.min(vals1); int posY1 = y + height - (int) Math.round((double) height * (minVal1 - minValue) / (maxValue - minValue)); int linePos = xposViolin + (individualPlotWidth / 2); g2d.setComposite(alphaComposite25); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, new float[]{2.0f}, 0.0f)); g2d.setColor(new Color(223, 36, 20)); g2d.drawLine(linePos, posY1 + 5, linePos, height + 120); g2d.setComposite(alphaComposite100); g2d.setFont(fontBoldSmall); g2d.setColor(new Color(223, 36, 20)); // print category name g2d.drawString(xLabels2[datasetNumber][category], linePos - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), height + 130); if (printTable && categoryCounter < categoryOrder.size()) { int yPos = height + 130 + 30 + (categoryCounter * tableElementHeight); g2d.drawString(xLabels2[datasetNumber][category], plotStart - 15 - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), yPos); } categoryCounter++; } // plot the wilcoxon result lines.. for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); int category1Index1 = categoryIndex[category1]; int category1Index2 = categoryIndex[category2]; int xpos1 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index1 + (individualPlotWidth / 2); int xpos2 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index2 + (individualPlotWidth / 2); double maxVal1 = JSci.maths.ArrayMath.max(vals[datasetNumber][category1]); double maxVal2 = JSci.maths.ArrayMath.max(vals[datasetNumber][category2]); int posY1 = y + height - (int) Math.round((double) height * (maxVal1 - minValue) / (maxValue - minValue)); int posY2 = y + height - (int) Math.round((double) height * (maxVal2 - minValue) / (maxValue - minValue)); int horizontalLineYPos = 0; if (posY1 < posY2) { horizontalLineYPos = posY1 - 25; } else { horizontalLineYPos = posY2 - 25; } int midpos = xpos1 + ((xpos2 - xpos1) / 2); double pValueWilcoxon = pvals[datasetNumber][category1][category2]; String pValueWilcoxonString = (new java.text.DecimalFormat("0.#E0", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); if (pValueWilcoxon > 0.001) { pValueWilcoxonString = (new java.text.DecimalFormat("##.###;-##.###", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); } g2d.setComposite(alphaComposite100); g2d.setColor(new Color(100, 100, 100)); if (printTable) { int yPos1 = height + 130 + 30 + (category1Index1 * tableElementHeight); int yPos2 = height + 130 + 30 + (category1Index2 * tableElementHeight); g2d.drawString(pValueWilcoxonString, xpos2 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos1); g2d.drawString(pValueWilcoxonString, xpos1 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos2); } else { g2d.drawLine(xpos1, posY1 - 3, xpos1, horizontalLineYPos); // vertical line 1 g2d.drawLine(xpos1, horizontalLineYPos, xpos2, horizontalLineYPos); // horizontal line g2d.drawLine(xpos2, posY2 - 3, xpos2, horizontalLineYPos); // vertical line 2 g2d.drawString(pValueWilcoxonString, midpos - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), horizontalLineYPos - 5); } } deltaX += datasetwidth + betweenDatasetMargin; datasetCounter++; } //Draw expression level indicator: g2d.setComposite(alphaComposite100); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); g2d.setColor(new Color(100, 100, 100)); int startVal = (int) Math.ceil(minValue); int endVal = (int) Math.floor(maxValue); int posY1 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (startVal - minValue) / (maxValue - minValue)); int posY2 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (endVal - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY1, marginLeft - 10, posY2); g2d.setFont(fontBold); for (int v = startVal; v <= endVal; v++) { int posY = marginTop + innerHeight - (int) Math.round((double) innerHeight * (v - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY, marginLeft - 20, posY); g2d.drawString(String.valueOf(v), marginLeft - 25 - (int) getWidth(String.valueOf(v), g2d.getFont()), posY + 3); } g2d.translate(marginLeft - 60, marginTop + innerHeight / 2); g2d.rotate(-0.5 * Math.PI); g2d.drawString("Relative gene expression", -(int) getWidth( "Relative gene expression", g2d.getFont()) / 2, 0); g2d.rotate(+0.5 * Math.PI); g2d.translate(-(marginLeft - 60), -(marginTop + innerHeight / 2)); g2d.dispose(); if (output == Output.PDF) { cb.restoreState(); document.close(); writer.close(); } else { bi.flush(); ImageIO.write(bi, output.toString().toLowerCase(), new File(outputFileName)); } Locale.setDefault(defaultLocale); } public void drawViolinPlot(Graphics2D g2d, int x, int y, int width, int height, double[] vals, double minValue, double maxValue) { int nrVals = vals.length; //Determine range of values: double minVals = JSci.maths.ArrayMath.min(vals); double maxVals = JSci.maths.ArrayMath.max(vals); //Make frequency distribution: int nrBins = 1 + (int) Math.round(Math.sqrt(nrVals) / 2d); int[] binCount = new int[nrBins]; for (int n = 0; n < nrBins; n++) { double lower = minVals + (maxVals - minVals) * (double) n / (double) nrBins; double upper = minVals + (maxVals - minVals) * (double) (n + 1) / (double) nrBins; for (int v = 0; v < nrVals; v++) { if (vals[v] >= lower && vals[v] < upper) { binCount[n]++; } } } //Smooth the distribution: int posYMin = y + height - (int) Math.round((double) height * (maxVals - minValue) / (maxValue - minValue)); int posYMax = y + height - (int) Math.round((double) height * (minVals - minValue) / (maxValue - minValue)); double[] posVal = new double[posYMax - posYMin + 1]; for (int pos = posYMin; pos <= posYMax; pos++) { double value = (((-pos + y + height) * (maxValue - minValue)) / (double) height) + minValue; for (int n = 0; n < nrBins; n++) { double lower = minVals + (maxVals - minVals) * (double) n / (double) nrBins; double upper = minVals + (maxVals - minVals) * (double) (n + 1) / (double) nrBins; if (value >= lower && value < upper) { posVal[pos - posYMin] = binCount[n]; } } } double kernelWidth = 10; double[] kernelWeights = new double[201]; for (int d = -100; d <= 100; d++) { double weight = java.lang.Math.pow(java.lang.Math.E, -((double) d / (double) kernelWidth) * ((double) d / (double) kernelWidth) / 2); kernelWeights[d + 100] = weight; } double[] posValSmoothed = new double[posYMax - posYMin + 1]; for (int pos = posYMin; pos <= posYMax; pos++) { double valSmoothed = 0; double sumWeights = 0; for (int q = pos - 100; q <= pos + 100; q++) { if (q >= posYMin && q <= posYMax) { sumWeights += kernelWeights[100 + q - pos]; valSmoothed += kernelWeights[100 + q - pos] * posVal[q - posYMin]; } } posValSmoothed[pos - posYMin] = valSmoothed / sumWeights; } double maxSmoothedVal = JSci.maths.ArrayMath.max(posValSmoothed); for (int pos = posYMin; pos <= posYMax; pos++) { posValSmoothed[pos - posYMin] /= maxSmoothedVal; } //Draw shape: GeneralPath path = new GeneralPath(); path.moveTo(x + width / 2, posYMin); for (int pos = posYMin; pos <= posYMax; pos++) { path.lineTo(x + width / 2 - posValSmoothed[pos - posYMin] * width / 2d - 1, pos); } for (int pos = posYMax; pos >= posYMin; pos--) { path.lineTo(x + width / 2 + posValSmoothed[pos - posYMin] * width / 2d + 1, pos); } path.closePath(); g2d.draw(path); g2d.fill(path); } public void drawBoxPlot(Graphics2D g2d, int x, int y, int width, int height, double[] vals, double minValue, double maxValue, boolean drawOutliers) { double median = JSci.maths.ArrayMath.percentile(vals, 0.50d); double q1 = JSci.maths.ArrayMath.percentile(vals, 0.25d); double q3 = JSci.maths.ArrayMath.percentile(vals, 0.75d); double iqr = q3 - q1; //Draw median: int posY = y + height - (int) Math.round((double) height * (median - minValue) / (maxValue - minValue)); g2d.setStroke(new java.awt.BasicStroke(2.0f, java.awt.BasicStroke.CAP_BUTT, java.awt.BasicStroke.JOIN_ROUND)); g2d.drawLine(x, posY, x + width, posY); //Draw IQR: int posY1 = y + height - (int) Math.round((double) height * (q3 - minValue) / (maxValue - minValue)); int posY2 = y + height - (int) Math.round((double) height * (q1 - minValue) / (maxValue - minValue)); g2d.setStroke(new java.awt.BasicStroke(1.0f, java.awt.BasicStroke.CAP_BUTT, java.awt.BasicStroke.JOIN_ROUND)); g2d.drawRect(x, posY1, width, posY2 - posY1); //Draw whiskers: double whiskerTop = q3 + 1.5d * iqr; double whiskerBottom = q1 - 1.5d * iqr; double max = JSci.maths.ArrayMath.max(vals); double min = JSci.maths.ArrayMath.min(vals); if (min > whiskerBottom) { whiskerBottom = min; } if (max < whiskerTop) { whiskerTop = max; } posY = y + height - (int) Math.round((double) height * (whiskerTop - minValue) / (maxValue - minValue)); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, new float[]{2.0f}, 0.0f)); g2d.drawLine(x + width / 2, posY, x + width / 2, posY1); g2d.setStroke(new java.awt.BasicStroke(1.0f, java.awt.BasicStroke.CAP_BUTT, java.awt.BasicStroke.JOIN_ROUND)); g2d.drawLine(x + width / 2 - 5, posY, x + width / 2 + 5, posY); posY = y + height - (int) Math.round((double) height * (whiskerBottom - minValue) / (maxValue - minValue)); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, new float[]{2.0f}, 0.0f)); g2d.drawLine(x + width / 2, posY2, x + width / 2, posY); g2d.setStroke(new java.awt.BasicStroke(1.0f, java.awt.BasicStroke.CAP_BUTT, java.awt.BasicStroke.JOIN_ROUND)); g2d.drawLine(x + width / 2 - 5, posY, x + width / 2 + 5, posY); //Draw outliers: if (drawOutliers) { java.awt.AlphaComposite alphaComposite10 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.10f); g2d.setComposite(alphaComposite10); for (int v = 0; v < vals.length; v++) { if (vals[v] > whiskerTop || vals[v] < whiskerBottom) { posY = y + height - (int) Math.round((double) height * (vals[v] - minValue) / (maxValue - minValue)); g2d.drawOval(x + width / 2 - 2, posY - 2, 5, 5); } } } } }
true
true
public void draw(double[][][] vals, String[] datasetNames, String[][] xLabels2, Output output, String outputFileName) throws IOException { Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); // set up Graphics2D depending on required format using iText in case PDF Graphics2D g2d = null; com.lowagie.text.Document document = null; com.lowagie.text.pdf.PdfWriter writer = null; com.lowagie.text.pdf.PdfContentByte cb = null; BufferedImage bi = null; // draw individual box/violinplots java.awt.AlphaComposite alphaComposite25 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.25f); java.awt.AlphaComposite alphaComposite50 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.50f); java.awt.AlphaComposite alphaComposite100 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.00f); float fontSize = 12f; java.awt.Font font = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, (int) fontSize); java.awt.Font fontBold = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, (int) fontSize); java.awt.Font fontSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, 8); java.awt.Font fontBoldSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, 8); int[] datasetWitdths = new int[datasetNames.length]; int individualPlotWidth = 70; int individualPlotMarginLeft = 10; int individualPlotMarginRight = 10; int betweenDatasetMargin = 20; int marginLeft = 100; int marginRight = 100; int marginTop = 100; int marginBottom = 100; int innerHeight = 500; int totalDatasetWidth = 0; int tableElementHeight = 25; boolean printTable = false; int maxNrCategories = 0; for (int x = 0; x < datasetNames.length; x++) { int nrCategoriesInDataset = vals[x].length; datasetWitdths[x] = nrCategoriesInDataset * (individualPlotWidth + individualPlotMarginLeft + individualPlotMarginRight); if (nrCategoriesInDataset > 2) { printTable = true; if (nrCategoriesInDataset > maxNrCategories) { maxNrCategories = nrCategoriesInDataset; } } totalDatasetWidth += datasetWitdths[x]; } totalDatasetWidth += (datasetNames.length - 1) * betweenDatasetMargin; int docWidth = marginLeft + marginRight + totalDatasetWidth; int docHeight = marginTop + marginBottom + innerHeight; if (printTable) { docHeight += (maxNrCategories * tableElementHeight); } if (output == Output.PDF) { com.lowagie.text.Rectangle rectangle = new com.lowagie.text.Rectangle(docWidth, docHeight); document = new com.lowagie.text.Document(rectangle); try { writer = com.lowagie.text.pdf.PdfWriter.getInstance(document, new java.io.FileOutputStream(outputFileName)); } catch (DocumentException e) { throw new IOException(e.fillInStackTrace()); } document.open(); cb = writer.getDirectContent(); cb.saveState(); //com.lowagie.text.pdf.DefaultFontMapper fontMap = new com.lowagie.text.pdf.DefaultFontMapper(); g2d = cb.createGraphics(docWidth, docHeight); } else { bi = new BufferedImage(docWidth, docHeight, BufferedImage.TYPE_INT_RGB); g2d = bi.createGraphics(); } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.white); g2d.fillRect(0, 0, docWidth, docHeight); double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; cern.jet.random.engine.RandomEngine randomEngine = new cern.jet.random.engine.DRand(); WilcoxonMannWhitney wmw = new WilcoxonMannWhitney(); double[][][] aucs = new double[vals.length][vals[0].length][vals[0].length]; double[][][] pvals = new double[vals.length][vals[0].length][vals[0].length]; for (int dataset = 0; dataset < datasetNames.length; dataset++) { double[][] valsForDs = vals[dataset]; // test between categories for (int category1 = 0; category1 < valsForDs.length; category1++) { double[] vals1 = valsForDs[category1]; double min1 = JSci.maths.ArrayMath.min(vals1); double max1 = JSci.maths.ArrayMath.max(vals1); if (min1 < minValue) { minValue = min1; } if (max1 > maxValue) { maxValue = max1; } for (int category2 = category1 + 1; category2 < valsForDs.length; category2++) { double[] vals2 = valsForDs[category2]; double pValueWilcoxon = wmw.returnWilcoxonMannWhitneyPValue(vals2, vals1); double auc = wmw.getAUC(); double min2 = JSci.maths.ArrayMath.min(vals2); double max2 = JSci.maths.ArrayMath.max(vals2); aucs[dataset][category1][category2] = auc; pvals[dataset][category1][category2] = pValueWilcoxon; if (max2 > maxValue) { maxValue = max2; } if (min2 < minValue) { minValue = min2; } } } } ArrayList<Pair<Double, Integer>> sortedPValuesPerDataset = new ArrayList<Pair<Double, Integer>>(); ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>> sortedPValuesPerCategory = new ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>>(); for (int dataset = 0; dataset < vals.length; dataset++) { // sort categories on the basis of their WMW results double[][] aucsfordataset = aucs[dataset]; double[][] pvaluesfordataset = pvals[dataset]; double minPvalueForDs = Double.MAX_VALUE; for (int category1 = 0; category1 < pvaluesfordataset.length; category1++) { for (int category2 = category1 + 1; category2 < pvaluesfordataset.length; category2++) { double valueToSort = pvaluesfordataset[category1][category2]; // if(sortByAUC){ // valueToSort = aucsfordataset[category1][category2]; // } sortedPValuesPerCategory.add(new Pair<Double, Triple<Integer, Integer, Integer>>(valueToSort, new Triple<Integer, Integer, Integer>(dataset, category1, category2), Pair.SORTBY.LEFT)); if (valueToSort < minPvalueForDs) { minPvalueForDs = valueToSort; } } } sortedPValuesPerDataset.add(new Pair<Double, Integer>(minPvalueForDs, dataset, Pair.SORTBY.LEFT)); } Collections.sort(sortedPValuesPerDataset, Collections.reverseOrder()); Collections.sort(sortedPValuesPerCategory, Collections.reverseOrder()); int datasetCounter = 0; int deltaX = 0; for (Pair<Double, Integer> pvalueDatasetPair : sortedPValuesPerDataset) { Integer datasetNumber = pvalueDatasetPair.getRight(); int datasetwidth = datasetWitdths[datasetNumber]; // draw the gradient g2d.setComposite(alphaComposite100); int x = marginLeft + deltaX; int height = innerHeight; java.awt.GradientPaint gradient = new java.awt.GradientPaint(0, marginTop, new Color(230, 230, 230), 0, height, new Color(250, 250, 250)); g2d.setPaint(gradient); g2d.fillRect(x - individualPlotMarginLeft / 2, marginTop - 90, datasetwidth, height + 100); // now get the sorted results per category within this dataset ArrayList<Triple<Integer, Integer, Integer>> sortedPValuesForDataset = new ArrayList<Triple<Integer, Integer, Integer>>(); for (Pair<Double, Triple<Integer, Integer, Integer>> pvalueTriplePair : sortedPValuesPerCategory) { System.out.println(pvalueTriplePair.toString()); if (pvalueTriplePair.getRight().getLeft().equals(datasetNumber)) { // this result belongs to this dataset sortedPValuesForDataset.add(pvalueTriplePair.getRight()); } } // reorder categories.. HashSet<Integer> visitedCategories = new HashSet<Integer>(); ArrayList<Integer> categoryOrder = new ArrayList<Integer>(); for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); if (!visitedCategories.contains(category1)) { categoryOrder.add(category1); visitedCategories.add(category1); } if (!visitedCategories.contains(category2)) { categoryOrder.add(category2); visitedCategories.add(category2); } } // print dataset name String datasetName = datasetNames[datasetNumber]; int y = marginTop; g2d.setColor(new Color(0, 0, 0)); g2d.setFont(fontBold); g2d.drawString(datasetName, x + 5, y - 70); g2d.setFont(font); // now we can plot the combinations between the categories (and their pvalues and aucs, yay!) int[] categoryIndex = new int[vals[datasetNumber].length]; int categoryCounter = 0; int plotStart = x + individualPlotMarginLeft; for (Integer category : categoryOrder) { double[] vals1 = vals[datasetNumber][category]; categoryIndex[category] = categoryCounter; // plot the individual box and violin plots g2d.setComposite(alphaComposite25); g2d.setColor(new Color(223, 36, 20)); int xposViolin = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * categoryCounter; int xposBoxPlot = xposViolin; // + (individualPlotWidth / 2 - 3) / 2; drawViolinPlot(g2d, xposViolin, y, individualPlotWidth, height, vals1, minValue, maxValue); g2d.setComposite(alphaComposite100); g2d.setColor(new Color(0, 0, 0)); drawBoxPlot(g2d, xposBoxPlot, y, individualPlotWidth, height, vals1, minValue, maxValue, false); // Draw bottom discrimator between candidate genes and other genes: double minVal1 = JSci.maths.ArrayMath.min(vals1); int posY1 = y + height - (int) Math.round((double) height * (minVal1 - minValue) / (maxValue - minValue)); int linePos = xposViolin + (individualPlotWidth / 2); g2d.setComposite(alphaComposite25); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, new float[]{2.0f}, 0.0f)); g2d.setColor(new Color(223, 36, 20)); g2d.drawLine(linePos, posY1 + 5, linePos, height + 120); g2d.setComposite(alphaComposite100); g2d.setFont(fontBoldSmall); g2d.setColor(new Color(223, 36, 20)); // print category name g2d.drawString(xLabels2[datasetNumber][category], linePos - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), height + 130); if (printTable && categoryCounter < categoryOrder.size()) { int yPos = height + 130 + 30 + (categoryCounter * tableElementHeight); g2d.drawString(xLabels2[datasetNumber][category], plotStart - 15 - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), yPos); } categoryCounter++; } // plot the wilcoxon result lines.. for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); int category1Index1 = categoryIndex[category1]; int category1Index2 = categoryIndex[category2]; int xpos1 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index1 + (individualPlotWidth / 2); int xpos2 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index2 + (individualPlotWidth / 2); double maxVal1 = JSci.maths.ArrayMath.max(vals[datasetNumber][category1]); double maxVal2 = JSci.maths.ArrayMath.max(vals[datasetNumber][category2]); int posY1 = y + height - (int) Math.round((double) height * (maxVal1 - minValue) / (maxValue - minValue)); int posY2 = y + height - (int) Math.round((double) height * (maxVal2 - minValue) / (maxValue - minValue)); int horizontalLineYPos = 0; if (posY1 < posY2) { horizontalLineYPos = posY1 - 25; } else { horizontalLineYPos = posY2 - 25; } int midpos = xpos1 + ((xpos2 - xpos1) / 2); double pValueWilcoxon = pvals[datasetNumber][category1][category2]; String pValueWilcoxonString = (new java.text.DecimalFormat("0.#E0", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); if (pValueWilcoxon > 0.001) { pValueWilcoxonString = (new java.text.DecimalFormat("##.###;-##.###", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); } g2d.setComposite(alphaComposite100); g2d.setColor(new Color(100, 100, 100)); if (printTable) { int yPos1 = height + 130 + 30 + (category1Index1 * tableElementHeight); int yPos2 = height + 130 + 30 + (category1Index2 * tableElementHeight); g2d.drawString(pValueWilcoxonString, xpos2 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos1); g2d.drawString(pValueWilcoxonString, xpos1 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos2); } else { g2d.drawLine(xpos1, posY1 - 3, xpos1, horizontalLineYPos); // vertical line 1 g2d.drawLine(xpos1, horizontalLineYPos, xpos2, horizontalLineYPos); // horizontal line g2d.drawLine(xpos2, posY2 - 3, xpos2, horizontalLineYPos); // vertical line 2 g2d.drawString(pValueWilcoxonString, midpos - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), horizontalLineYPos - 5); } } deltaX += datasetwidth + betweenDatasetMargin; datasetCounter++; } //Draw expression level indicator: g2d.setComposite(alphaComposite100); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); g2d.setColor(new Color(100, 100, 100)); int startVal = (int) Math.ceil(minValue); int endVal = (int) Math.floor(maxValue); int posY1 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (startVal - minValue) / (maxValue - minValue)); int posY2 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (endVal - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY1, marginLeft - 10, posY2); g2d.setFont(fontBold); for (int v = startVal; v <= endVal; v++) { int posY = marginTop + innerHeight - (int) Math.round((double) innerHeight * (v - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY, marginLeft - 20, posY); g2d.drawString(String.valueOf(v), marginLeft - 25 - (int) getWidth(String.valueOf(v), g2d.getFont()), posY + 3); } g2d.translate(marginLeft - 60, marginTop + innerHeight / 2); g2d.rotate(-0.5 * Math.PI); g2d.drawString("Relative gene expression", -(int) getWidth( "Relative gene expression", g2d.getFont()) / 2, 0); g2d.rotate(+0.5 * Math.PI); g2d.translate(-(marginLeft - 60), -(marginTop + innerHeight / 2)); g2d.dispose(); if (output == Output.PDF) { cb.restoreState(); document.close(); writer.close(); } else { bi.flush(); ImageIO.write(bi, output.toString().toLowerCase(), new File(outputFileName)); } Locale.setDefault(defaultLocale); }
public void draw(double[][][] vals, String[] datasetNames, String[][] xLabels2, Output output, String outputFileName) throws IOException { Locale defaultLocale = Locale.getDefault(); Locale.setDefault(Locale.US); // set up Graphics2D depending on required format using iText in case PDF Graphics2D g2d = null; com.lowagie.text.Document document = null; com.lowagie.text.pdf.PdfWriter writer = null; com.lowagie.text.pdf.PdfContentByte cb = null; BufferedImage bi = null; // draw individual box/violinplots java.awt.AlphaComposite alphaComposite25 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.25f); java.awt.AlphaComposite alphaComposite50 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_OVER, 0.50f); java.awt.AlphaComposite alphaComposite100 = java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC, 1.00f); float fontSize = 12f; java.awt.Font font = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, (int) fontSize); java.awt.Font fontBold = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, (int) fontSize); java.awt.Font fontSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.PLAIN, 8); java.awt.Font fontBoldSmall = new java.awt.Font("Gill Sans MT", java.awt.Font.BOLD, 8); int[] datasetWitdths = new int[datasetNames.length]; int individualPlotWidth = 70; int individualPlotMarginLeft = 10; int individualPlotMarginRight = 10; int betweenDatasetMargin = 20; int marginLeft = 100; int marginRight = 100; int marginTop = 100; int marginBottom = 100; int innerHeight = 500; int totalDatasetWidth = 0; int tableElementHeight = 25; boolean printTable = false; int maxNrCategories = 0; for (int x = 0; x < datasetNames.length; x++) { int nrCategoriesInDataset = vals[x].length; datasetWitdths[x] = nrCategoriesInDataset * (individualPlotWidth + individualPlotMarginLeft + individualPlotMarginRight); if (nrCategoriesInDataset > 2) { printTable = true; if (nrCategoriesInDataset > maxNrCategories) { maxNrCategories = nrCategoriesInDataset; } } totalDatasetWidth += datasetWitdths[x]; } totalDatasetWidth += (datasetNames.length - 1) * betweenDatasetMargin; int docWidth = marginLeft + marginRight + totalDatasetWidth; int docHeight = marginTop + marginBottom + innerHeight; if (printTable) { docHeight += (maxNrCategories * tableElementHeight); } if (output == Output.PDF) { com.lowagie.text.Rectangle rectangle = new com.lowagie.text.Rectangle(docWidth, docHeight); document = new com.lowagie.text.Document(rectangle); try { writer = com.lowagie.text.pdf.PdfWriter.getInstance(document, new java.io.FileOutputStream(outputFileName)); } catch (DocumentException e) { throw new IOException(e.fillInStackTrace()); } document.open(); cb = writer.getDirectContent(); cb.saveState(); //com.lowagie.text.pdf.DefaultFontMapper fontMap = new com.lowagie.text.pdf.DefaultFontMapper(); g2d = cb.createGraphics(docWidth, docHeight); } else { bi = new BufferedImage(docWidth, docHeight, BufferedImage.TYPE_INT_RGB); g2d = bi.createGraphics(); } g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.white); g2d.fillRect(0, 0, docWidth, docHeight); double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; // cern.jet.random.engine.RandomEngine randomEngine = new cern.jet.random.engine.DRand(); WilcoxonMannWhitney wmw = new WilcoxonMannWhitney(); double[][][] aucs = new double[vals.length][vals[0].length][vals[0].length]; double[][][] pvals = new double[vals.length][vals[0].length][vals[0].length]; for (int dataset = 0; dataset < datasetNames.length; dataset++) { double[][] valsForDs = vals[dataset]; // test between categories for (int category1 = 0; category1 < valsForDs.length; category1++) { double[] vals1 = valsForDs[category1]; double min1 = JSci.maths.ArrayMath.min(vals1); double max1 = JSci.maths.ArrayMath.max(vals1); if (min1 < minValue) { minValue = min1; } if (max1 > maxValue) { maxValue = max1; } for (int category2 = category1 + 1; category2 < valsForDs.length; category2++) { double[] vals2 = valsForDs[category2]; double pValueWilcoxon = wmw.returnWilcoxonMannWhitneyPValue(vals2, vals1); double auc = wmw.getAUC(); double min2 = JSci.maths.ArrayMath.min(vals2); double max2 = JSci.maths.ArrayMath.max(vals2); aucs[dataset][category1][category2] = auc; pvals[dataset][category1][category2] = pValueWilcoxon; if (max2 > maxValue) { maxValue = max2; } if (min2 < minValue) { minValue = min2; } } } } ArrayList<Pair<Double, Integer>> sortedPValuesPerDataset = new ArrayList<Pair<Double, Integer>>(); ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>> sortedPValuesPerCategory = new ArrayList<Pair<Double, Triple<Integer, Integer, Integer>>>(); for (int dataset = 0; dataset < vals.length; dataset++) { // sort categories on the basis of their WMW results double[][] aucsfordataset = aucs[dataset]; double[][] pvaluesfordataset = pvals[dataset]; double minPvalueForDs = Double.MAX_VALUE; for (int category1 = 0; category1 < pvaluesfordataset.length; category1++) { for (int category2 = category1 + 1; category2 < pvaluesfordataset.length; category2++) { double valueToSort = pvaluesfordataset[category1][category2]; // if(sortByAUC){ // valueToSort = aucsfordataset[category1][category2]; // } sortedPValuesPerCategory.add(new Pair<Double, Triple<Integer, Integer, Integer>>(valueToSort, new Triple<Integer, Integer, Integer>(dataset, category1, category2), Pair.SORTBY.LEFT)); if (valueToSort < minPvalueForDs) { minPvalueForDs = valueToSort; } } } sortedPValuesPerDataset.add(new Pair<Double, Integer>(minPvalueForDs, dataset, Pair.SORTBY.LEFT)); } Collections.sort(sortedPValuesPerDataset, Collections.reverseOrder()); Collections.sort(sortedPValuesPerCategory, Collections.reverseOrder()); int datasetCounter = 0; int deltaX = 0; for (Pair<Double, Integer> pvalueDatasetPair : sortedPValuesPerDataset) { Integer datasetNumber = pvalueDatasetPair.getRight(); int datasetwidth = datasetWitdths[datasetNumber]; // draw the gradient g2d.setComposite(alphaComposite100); int x = marginLeft + deltaX; int height = innerHeight; java.awt.GradientPaint gradient = new java.awt.GradientPaint(0, marginTop, new Color(230, 230, 230), 0, height, new Color(250, 250, 250)); g2d.setPaint(gradient); g2d.fillRect(x - individualPlotMarginLeft / 2, marginTop - 90, datasetwidth, height + 100); // now get the sorted results per category within this dataset ArrayList<Triple<Integer, Integer, Integer>> sortedPValuesForDataset = new ArrayList<Triple<Integer, Integer, Integer>>(); for (Pair<Double, Triple<Integer, Integer, Integer>> pvalueTriplePair : sortedPValuesPerCategory) { System.out.println(pvalueTriplePair.toString()); if (pvalueTriplePair.getRight().getLeft().equals(datasetNumber)) { // this result belongs to this dataset sortedPValuesForDataset.add(pvalueTriplePair.getRight()); } } // reorder categories.. HashSet<Integer> visitedCategories = new HashSet<Integer>(); ArrayList<Integer> categoryOrder = new ArrayList<Integer>(); for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); if (!visitedCategories.contains(category1)) { categoryOrder.add(category1); visitedCategories.add(category1); } if (!visitedCategories.contains(category2)) { categoryOrder.add(category2); visitedCategories.add(category2); } } // print dataset name String datasetName = datasetNames[datasetNumber]; int y = marginTop; g2d.setColor(new Color(0, 0, 0)); g2d.setFont(fontBold); g2d.drawString(datasetName, x + 5, y - 70); g2d.setFont(font); // now we can plot the combinations between the categories (and their pvalues and aucs, yay!) int[] categoryIndex = new int[vals[datasetNumber].length]; int categoryCounter = 0; int plotStart = x + individualPlotMarginLeft; for (Integer category : categoryOrder) { double[] vals1 = vals[datasetNumber][category]; categoryIndex[category] = categoryCounter; // plot the individual box and violin plots g2d.setComposite(alphaComposite25); g2d.setColor(new Color(223, 36, 20)); int xposViolin = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * categoryCounter; int xposBoxPlot = xposViolin; // + (individualPlotWidth / 2 - 3) / 2; drawViolinPlot(g2d, xposViolin, y, individualPlotWidth, height, vals1, minValue, maxValue); g2d.setComposite(alphaComposite100); g2d.setColor(new Color(0, 0, 0)); drawBoxPlot(g2d, xposBoxPlot, y, individualPlotWidth, height, vals1, minValue, maxValue, false); // Draw bottom discrimator between candidate genes and other genes: double minVal1 = JSci.maths.ArrayMath.min(vals1); int posY1 = y + height - (int) Math.round((double) height * (minVal1 - minValue) / (maxValue - minValue)); int linePos = xposViolin + (individualPlotWidth / 2); g2d.setComposite(alphaComposite25); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f, new float[]{2.0f}, 0.0f)); g2d.setColor(new Color(223, 36, 20)); g2d.drawLine(linePos, posY1 + 5, linePos, height + 120); g2d.setComposite(alphaComposite100); g2d.setFont(fontBoldSmall); g2d.setColor(new Color(223, 36, 20)); // print category name g2d.drawString(xLabels2[datasetNumber][category], linePos - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), height + 130); if (printTable && categoryCounter < categoryOrder.size()) { int yPos = height + 130 + 30 + (categoryCounter * tableElementHeight); g2d.drawString(xLabels2[datasetNumber][category], plotStart - 15 - (int) Math.round(getWidth(xLabels2[datasetNumber][category], g2d.getFont()) / 2), yPos); } categoryCounter++; } // plot the wilcoxon result lines.. for (Triple<Integer, Integer, Integer> datasetCategoryCombo : sortedPValuesForDataset) { Integer category1 = datasetCategoryCombo.getMiddle(); Integer category2 = datasetCategoryCombo.getRight(); int category1Index1 = categoryIndex[category1]; int category1Index2 = categoryIndex[category2]; int xpos1 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index1 + (individualPlotWidth / 2); int xpos2 = plotStart - 5 + (individualPlotMarginLeft + individualPlotWidth + individualPlotMarginRight) * category1Index2 + (individualPlotWidth / 2); double maxVal1 = JSci.maths.ArrayMath.max(vals[datasetNumber][category1]); double maxVal2 = JSci.maths.ArrayMath.max(vals[datasetNumber][category2]); int posY1 = y + height - (int) Math.round((double) height * (maxVal1 - minValue) / (maxValue - minValue)); int posY2 = y + height - (int) Math.round((double) height * (maxVal2 - minValue) / (maxValue - minValue)); int horizontalLineYPos = 0; if (posY1 < posY2) { horizontalLineYPos = posY1 - 25; } else { horizontalLineYPos = posY2 - 25; } int midpos = xpos1 + ((xpos2 - xpos1) / 2); double pValueWilcoxon = pvals[datasetNumber][category1][category2]; String pValueWilcoxonString = (new java.text.DecimalFormat("0.#E0", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); if (pValueWilcoxon > 0.001) { pValueWilcoxonString = (new java.text.DecimalFormat("##.###;-##.###", new java.text.DecimalFormatSymbols(java.util.Locale.US))).format(pValueWilcoxon); } g2d.setComposite(alphaComposite100); g2d.setColor(new Color(100, 100, 100)); if (printTable) { int yPos1 = height + 130 + 30 + (category1Index1 * tableElementHeight); int yPos2 = height + 130 + 30 + (category1Index2 * tableElementHeight); g2d.drawString(pValueWilcoxonString, xpos2 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos1); g2d.drawString(pValueWilcoxonString, xpos1 - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), yPos2); } else { g2d.drawLine(xpos1, posY1 - 3, xpos1, horizontalLineYPos); // vertical line 1 g2d.drawLine(xpos1, horizontalLineYPos, xpos2, horizontalLineYPos); // horizontal line g2d.drawLine(xpos2, posY2 - 3, xpos2, horizontalLineYPos); // vertical line 2 g2d.drawString(pValueWilcoxonString, midpos - (int) Math.round(getWidth(pValueWilcoxonString, g2d.getFont()) / 2), horizontalLineYPos - 5); } } deltaX += datasetwidth + betweenDatasetMargin; datasetCounter++; } //Draw expression level indicator: g2d.setComposite(alphaComposite100); g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); g2d.setColor(new Color(100, 100, 100)); int startVal = (int) Math.ceil(minValue); int endVal = (int) Math.floor(maxValue); int posY1 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (startVal - minValue) / (maxValue - minValue)); int posY2 = marginTop + innerHeight - (int) Math.round((double) innerHeight * (endVal - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY1, marginLeft - 10, posY2); g2d.setFont(fontBold); for (int v = startVal; v <= endVal; v++) { int posY = marginTop + innerHeight - (int) Math.round((double) innerHeight * (v - minValue) / (maxValue - minValue)); g2d.drawLine(marginLeft - 10, posY, marginLeft - 20, posY); g2d.drawString(String.valueOf(v), marginLeft - 25 - (int) getWidth(String.valueOf(v), g2d.getFont()), posY + 3); } g2d.translate(marginLeft - 60, marginTop + innerHeight / 2); g2d.rotate(-0.5 * Math.PI); g2d.drawString("Relative gene expression", -(int) getWidth( "Relative gene expression", g2d.getFont()) / 2, 0); g2d.rotate(+0.5 * Math.PI); g2d.translate(-(marginLeft - 60), -(marginTop + innerHeight / 2)); g2d.dispose(); if (output == Output.PDF) { cb.restoreState(); document.close(); writer.close(); } else { bi.flush(); ImageIO.write(bi, output.toString().toLowerCase(), new File(outputFileName)); } Locale.setDefault(defaultLocale); }
diff --git a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/SimpleBee.java b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/SimpleBee.java index aaad87f..e0bd41c 100644 --- a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/SimpleBee.java +++ b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/SimpleBee.java @@ -1,480 +1,481 @@ package harvard.robobees.simbeeotic.model; import com.bulletphysics.collision.shapes.CollisionShape; import com.bulletphysics.collision.shapes.SphereShape; import com.bulletphysics.dynamics.DiscreteDynamicsWorld; import com.bulletphysics.dynamics.RigidBody; import com.bulletphysics.dynamics.RigidBodyConstructionInfo; import com.bulletphysics.linearmath.MatrixUtil; import com.bulletphysics.linearmath.MotionState; import com.bulletphysics.linearmath.Transform; import com.bulletphysics.linearmath.QuaternionUtil; import com.google.inject.Inject; import com.google.inject.name.Named; import harvard.robobees.simbeeotic.environment.PhysicalConstants; import harvard.robobees.simbeeotic.util.MathUtil; import harvard.robobees.simbeeotic.SimTime; import harvard.robobees.simbeeotic.model.weather.WeatherModel; import javax.vecmath.Quat4f; import javax.vecmath.Vector3f; import java.util.concurrent.TimeUnit; import java.awt.*; /** * A simple bee platform that can be used as a starting point for creating * more complicated bee models. This base class creates a physical body in * the world (a sphere) and has primitive flight controls to simplify * movement. Sensors and a radio can be attached at runtime and the logic is * supplied as user-defined behavior. * * @author bkate */ public abstract class SimpleBee extends GenericModel { // parameters private float length = 0.2f; // m private float mass = 0.128f; // g private float maxAccel = 1.0f; // m/s^2 private long kinematicUpdateRate = 100; // ms private double actuationEnergy = 600; // mA private float actuationErrTurnVar = 0; // radians private float actuationErrDirVar = 0; // percent (0-1 scale) private float actuationErrVelVar = 0; // percent (0-1 scale) private boolean useWind = false; private boolean compensateForWind = true; protected Timer kinematicTimer; // physical state private RigidBody body; private Vector3f desiredLinVel = new Vector3f(); private Vector3f hoverForce; private boolean hovering = false; /** {@inheritDoc} */ @Override public void initialize() { super.initialize(); // get the weather model, if one exists final WeatherModel weather = getSimEngine().findModelByType(WeatherModel.class); // setup a timer that handles the details of using the simple flight abstraction if (kinematicUpdateRate > 0) { kinematicTimer = createTimer(new TimerCallback() { public void fire(SimTime time) { clearForces(); updateKinematics(time); if (hovering || (desiredLinVel.length() > 0)) { // todo: replace this with model based on the force applied? getAggregator().addValue("energy", "actuation", actuationEnergy * kinematicUpdateRate / TimeUnit.SECONDS.toMillis(1)); body.activate(); // apply changes to motion // desired final direction in body frame Vector3f impulse = new Vector3f(desiredLinVel); float impulseMag = impulse.length(); // apply some actation error to the direction of // the velocity vector to make it go off course if ((impulseMag > 0) && (actuationErrDirVar > 0)) { impulse.normalize(); impulse.x += getRandom().nextGaussian() * actuationErrDirVar; impulse.y += getRandom().nextGaussian() * actuationErrDirVar; impulse.z += getRandom().nextGaussian() * actuationErrDirVar; impulse.normalize(); impulse.scale(impulseMag); } // apply some actation error to the magnitude of the velocity so that // the bee may go further/shorter than expected if ((impulseMag > 0) && (actuationErrVelVar > 0)) { impulseMag += (impulseMag * getRandom().nextGaussian() * actuationErrVelVar); impulse.normalize(); impulse.scale(impulseMag); } Transform trans = new Transform(); // translate to world frame trans.setIdentity(); trans.setRotation(getTruthOrientation()); trans.transform(impulse); // find the velocity change and determine the instantaneous acceleration required impulse.sub(getTruthLinearVelocity()); + impulseMag = impulse.length(); // cap the translational force based on the max acceleration ability if (impulseMag > maxAccel) { impulse.normalize(); impulse.scale(maxAccel); } // apply an instantaneous force to get the desired velocity change impulse.scale(getMass()); applyImpulse(impulse); } // apply wind effects if (useWind && (weather != null)) { Vector3f windVel = weather.getWindVelocity(time, getTruthPosition()); Vector3f windForce = new Vector3f(windVel); windForce.normalize(); double speed = windVel.length(); double area = length / 2; area *= area * Math.PI; // calculate wind force double force = 0.5 * PhysicalConstants.AIR_DENSITY * speed * speed * area; windForce.scale((float)force); if (!compensateForWind) { applyForce(windForce); } } // todo: drag? // account for gravity (or not) if (hovering) { body.activate(); applyForce(hoverForce); } } }, 0, TimeUnit.MILLISECONDS, kinematicUpdateRate, TimeUnit.MILLISECONDS); } } /** {@inheritDoc} */ @Override protected RigidBody initializeBody(DiscreteDynamicsWorld world) { float halfLength = length / 2; // establish the bee body CollisionShape colShape = new SphereShape(halfLength); Transform startTransform = new Transform(); startTransform.setIdentity(); Vector3f localInertia = new Vector3f(0, 0, 0); colShape.calculateLocalInertia(mass, localInertia); Vector3f start = getStartPosition(); start.z += halfLength; startTransform.origin.set(start); int id = getObjectId(); getMotionRecorder().initializeObject(id, colShape); getMotionRecorder().updateMetadata(id, new Color(238, 201, 0), null, getName()); MotionState myMotionState = new RecordedMotionState(id, getMotionRecorder(), startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); // modify the thresholds for deactivating the bee // because it moves at a much smaller scale rbInfo.linearSleepingThreshold = 0.08f; // m/s rbInfo.angularSleepingThreshold = 0.1f; // rad/s body = new RigidBody(rbInfo); // todo: put the bee's properties into the entity info? body.setUserPointer(new EntityInfo(id)); // bees do not collide with each other or the hive world.addRigidBody(body, COLLISION_BEE, (short)(COLLISION_TERRAIN | COLLISION_FLOWER)); hoverForce = new Vector3f(0, 0, mass * (float)-PhysicalConstants.EARTH_GRAVITY); return body; } /** {@inheritDoc} */ @Override public void finish() { } /** * A method that is called by the kinematic timer. Derived classes are expected to implement * movemement functionality with this callback. * * @param time The current time. */ protected void updateKinematics(SimTime time) { // default implementation does nothing, override to suit your needs } /** * Performs an instantaneous right-handed rotation of the body about the Z axis. The results of * this call will be visible immediately through the bee's sensors. At the same time, the rotation * about the X and Y axes are reset to zero (emulating level flight) and the angular velocity is * set to zero. * * @param angle The angle of rotation (rad). */ protected final void turn(final float angle) { body.activate(); body.setAngularVelocity(new Vector3f()); Transform orient = new Transform(); orient.setIdentity(); orient.setRotation(getTruthOrientation()); Vector3f unitX = new Vector3f(1, 0, 0); orient.transform(unitX); float ang = angle; if (actuationErrTurnVar > 0) { ang += getRandom().nextGaussian() * actuationErrTurnVar; } float heading = (float)Math.atan2(unitX.y, unitX.x) + ang; Quat4f quat = new Quat4f(); MatrixUtil.getRotation(MathUtil.eulerZYXtoDCM(0, 0, heading), quat); body.getWorldTransform(orient); orient.setRotation(quat); body.setWorldTransform(orient); } /** * Performs an instantaneous rotation of the body to point in the direction of the given point. The results of * this call will be visible immediately through the bee's sensors. * * @param point The point in space toward which this bee will be rotated (in the world frame). */ protected final void turnToward(final Vector3f point) { body.activate(); Vector3f currPos = getTruthPosition(); Vector3f diff = new Vector3f(); Vector3f unitX = new Vector3f(1, 0, 0); diff.sub(point, currPos); diff.normalize(); Vector3f axis = new Vector3f(); axis.cross(unitX, diff); axis.normalize(); if (Float.isNaN(axis.length())) { axis = new Vector3f(0, 0, 1); } float angle = (float)Math.acos(unitX.dot(diff)); if (Float.isNaN(angle)) { return; } if (actuationErrTurnVar > 0) { angle += getRandom().nextGaussian() * actuationErrTurnVar; } Transform trans = new Transform(); Quat4f rot = new Quat4f(); QuaternionUtil.setRotation(rot, axis, angle); body.getWorldTransform(trans); trans.setRotation(rot); body.setWorldTransform(trans); } /** * Sets the linear velocity of the bee. The results of this * call will not be seen immediately, but applied to future movement * and maintained until modified. * * <br/> * If the linear velocity is set to zero, the bee will fall to the ground due * to the effects of gravity. To counteract this, enable hover mode. * * @param vel The desired linear velocity of the bee for the next time step (m/s, in the body frame). */ protected final void setDesiredLinearVelocity(final Vector3f vel) { desiredLinVel = vel; } /** * Gets the linear velocity that this bee's automated flight control is * attempting to maintain. * * @return The linear velocity (m/s in the body frame). */ protected final Vector3f getDesiredLinearVelocity() { return new Vector3f(desiredLinVel); } /** * Enables/disables hover mode for this bee. If enabled, the bee's automated * flight control will apply a force to counteract gravity. This allows the * bee to have zero linear velocity and maintain a position off the ground. * * @param hover True if hovering should be enabled for the future, false otherwise. */ protected final void setHovering(final boolean hover) { hovering = hover; } /** * Indicates if hovering mode is enabled or disabled. * * @return True if hover mode is enabled for the future, false otherwise. */ protected final boolean isHovering() { return hovering; } public final float getLength() { return length; } public final float getMass() { return mass; } @Override public String toString() { return "SimpleBee " + getModelId() + " " + getObjectId(); } @Inject(optional = true) public final void setLength(@Named("length") final float length) { if (!isInitialized()) { this.length = length; } } @Inject(optional = true) public final void setMass(@Named("mass") final float mass) { if (!isInitialized()) { this.mass = mass; } } @Inject(optional = true) public final void setMaxAcceleration(@Named("max-acceleration") final float max) { if (!isInitialized()) { this.maxAccel = max; } } @Inject(optional = true) public final void setKinematicUpdateRate(@Named("kinematic-update-rate") final long rate) { if (!isInitialized()) { this.kinematicUpdateRate = rate; } } @Inject(optional = true) public final void setUseWind(@Named("use-wind") final boolean use) { if (!isInitialized()) { this.useWind = use; } } @Inject(optional = true) public final void setUseWindCompensation(@Named("wind-compensation") final boolean use) { if (!isInitialized()) { this.compensateForWind = use; } } @Inject(optional = true) public final void setActuationEnergy(@Named("actuation-energy") final double energy) { if (!isInitialized()) { this.actuationEnergy = energy; } } @Inject(optional = true) public final void setActuationErrTurnVar(@Named("actuation-error-turn-var") final float err) { if (!isInitialized()) { this.actuationErrTurnVar = err; } } @Inject(optional = true) public final void setActuationDirTurnVar(@Named("actuation-error-dir-var") final float err) { if (!isInitialized()) { this.actuationErrDirVar = err; } } @Inject(optional = true) public final void setActuationVelTurnVar(@Named("actuation-error-vel-var") final float err) { if (!isInitialized()) { this.actuationErrVelVar = err; } } }
true
true
public void initialize() { super.initialize(); // get the weather model, if one exists final WeatherModel weather = getSimEngine().findModelByType(WeatherModel.class); // setup a timer that handles the details of using the simple flight abstraction if (kinematicUpdateRate > 0) { kinematicTimer = createTimer(new TimerCallback() { public void fire(SimTime time) { clearForces(); updateKinematics(time); if (hovering || (desiredLinVel.length() > 0)) { // todo: replace this with model based on the force applied? getAggregator().addValue("energy", "actuation", actuationEnergy * kinematicUpdateRate / TimeUnit.SECONDS.toMillis(1)); body.activate(); // apply changes to motion // desired final direction in body frame Vector3f impulse = new Vector3f(desiredLinVel); float impulseMag = impulse.length(); // apply some actation error to the direction of // the velocity vector to make it go off course if ((impulseMag > 0) && (actuationErrDirVar > 0)) { impulse.normalize(); impulse.x += getRandom().nextGaussian() * actuationErrDirVar; impulse.y += getRandom().nextGaussian() * actuationErrDirVar; impulse.z += getRandom().nextGaussian() * actuationErrDirVar; impulse.normalize(); impulse.scale(impulseMag); } // apply some actation error to the magnitude of the velocity so that // the bee may go further/shorter than expected if ((impulseMag > 0) && (actuationErrVelVar > 0)) { impulseMag += (impulseMag * getRandom().nextGaussian() * actuationErrVelVar); impulse.normalize(); impulse.scale(impulseMag); } Transform trans = new Transform(); // translate to world frame trans.setIdentity(); trans.setRotation(getTruthOrientation()); trans.transform(impulse); // find the velocity change and determine the instantaneous acceleration required impulse.sub(getTruthLinearVelocity()); // cap the translational force based on the max acceleration ability if (impulseMag > maxAccel) { impulse.normalize(); impulse.scale(maxAccel); } // apply an instantaneous force to get the desired velocity change impulse.scale(getMass()); applyImpulse(impulse); } // apply wind effects if (useWind && (weather != null)) { Vector3f windVel = weather.getWindVelocity(time, getTruthPosition()); Vector3f windForce = new Vector3f(windVel); windForce.normalize(); double speed = windVel.length(); double area = length / 2; area *= area * Math.PI; // calculate wind force double force = 0.5 * PhysicalConstants.AIR_DENSITY * speed * speed * area; windForce.scale((float)force); if (!compensateForWind) { applyForce(windForce); } } // todo: drag? // account for gravity (or not) if (hovering) { body.activate(); applyForce(hoverForce); } } }, 0, TimeUnit.MILLISECONDS, kinematicUpdateRate, TimeUnit.MILLISECONDS); } }
public void initialize() { super.initialize(); // get the weather model, if one exists final WeatherModel weather = getSimEngine().findModelByType(WeatherModel.class); // setup a timer that handles the details of using the simple flight abstraction if (kinematicUpdateRate > 0) { kinematicTimer = createTimer(new TimerCallback() { public void fire(SimTime time) { clearForces(); updateKinematics(time); if (hovering || (desiredLinVel.length() > 0)) { // todo: replace this with model based on the force applied? getAggregator().addValue("energy", "actuation", actuationEnergy * kinematicUpdateRate / TimeUnit.SECONDS.toMillis(1)); body.activate(); // apply changes to motion // desired final direction in body frame Vector3f impulse = new Vector3f(desiredLinVel); float impulseMag = impulse.length(); // apply some actation error to the direction of // the velocity vector to make it go off course if ((impulseMag > 0) && (actuationErrDirVar > 0)) { impulse.normalize(); impulse.x += getRandom().nextGaussian() * actuationErrDirVar; impulse.y += getRandom().nextGaussian() * actuationErrDirVar; impulse.z += getRandom().nextGaussian() * actuationErrDirVar; impulse.normalize(); impulse.scale(impulseMag); } // apply some actation error to the magnitude of the velocity so that // the bee may go further/shorter than expected if ((impulseMag > 0) && (actuationErrVelVar > 0)) { impulseMag += (impulseMag * getRandom().nextGaussian() * actuationErrVelVar); impulse.normalize(); impulse.scale(impulseMag); } Transform trans = new Transform(); // translate to world frame trans.setIdentity(); trans.setRotation(getTruthOrientation()); trans.transform(impulse); // find the velocity change and determine the instantaneous acceleration required impulse.sub(getTruthLinearVelocity()); impulseMag = impulse.length(); // cap the translational force based on the max acceleration ability if (impulseMag > maxAccel) { impulse.normalize(); impulse.scale(maxAccel); } // apply an instantaneous force to get the desired velocity change impulse.scale(getMass()); applyImpulse(impulse); } // apply wind effects if (useWind && (weather != null)) { Vector3f windVel = weather.getWindVelocity(time, getTruthPosition()); Vector3f windForce = new Vector3f(windVel); windForce.normalize(); double speed = windVel.length(); double area = length / 2; area *= area * Math.PI; // calculate wind force double force = 0.5 * PhysicalConstants.AIR_DENSITY * speed * speed * area; windForce.scale((float)force); if (!compensateForWind) { applyForce(windForce); } } // todo: drag? // account for gravity (or not) if (hovering) { body.activate(); applyForce(hoverForce); } } }, 0, TimeUnit.MILLISECONDS, kinematicUpdateRate, TimeUnit.MILLISECONDS); } }
diff --git a/src/main/java/org/jenkinsci/plugins/vsphere/tools/VSphere.java b/src/main/java/org/jenkinsci/plugins/vsphere/tools/VSphere.java index 2ba65cf..4aeb046 100644 --- a/src/main/java/org/jenkinsci/plugins/vsphere/tools/VSphere.java +++ b/src/main/java/org/jenkinsci/plugins/vsphere/tools/VSphere.java @@ -1,621 +1,626 @@ /* Copyright 2013, MANDIANT, Eric Lordahl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jenkinsci.plugins.vsphere.tools; import java.net.MalformedURLException; import java.net.URL; import java.rmi.RemoteException; import com.vmware.vim25.*; import com.vmware.vim25.mo.Datastore; import com.vmware.vim25.mo.ClusterComputeResource; import com.vmware.vim25.mo.Folder; import com.vmware.vim25.mo.InventoryNavigator; import com.vmware.vim25.mo.ManagedEntity; import com.vmware.vim25.mo.ResourcePool; import com.vmware.vim25.mo.ServiceInstance; import com.vmware.vim25.mo.Task; import com.vmware.vim25.mo.VirtualMachine; import com.vmware.vim25.mo.VirtualMachineSnapshot; public class VSphere { private final URL url; private final String session; private VSphere(String url, String user, String pw) throws VSphereException{ try { //TODO - change ignoreCert to be configurable this.url = new URL(url); this.session = (new ServiceInstance(this.url, user, pw, true)).getServerConnection().getSessionStr(); } catch (Exception e) { throw new VSphereException(e); } } private ServiceInstance getServiceInstance() throws RemoteException, MalformedURLException{ return new ServiceInstance(url, session, true); } /** * Initiates Connection to vSphere Server * @throws VSphereException */ public static VSphere connect(String server, String user, String pw) throws VSphereException { return new VSphere(server, user, pw); } public static String vSphereOutput(String msg){ return (Messages.VSphereLogger_title()+": ").concat(msg); } /** * Creates a new VM from a given template with a given name. * * @param cloneName - name of VM to be created * @param sourceName - name of VM or template to be cloned * @param linkedClone - true if you want to re-use disk backings * @param resourcePool - resource pool to use * @param cluster - ComputeClusterResource to use * @param datastoreName - Datastore to use * @throws VSphereException */ public void cloneVm(String cloneName, String sourceName, boolean linkedClone, String resourcePool, String cluster, String datastoreName) throws VSphereException { System.out.println("Creating a shallow clone of \""+ sourceName + "\" to \""+cloneName+"\""); try{ VirtualMachine sourceVm = getVmByName(sourceName); if(sourceVm==null) { throw new VSphereException("No VM or template " + sourceName + " found"); } if(getVmByName(cloneName)!=null){ throw new VSphereException("VM " + cloneName + " already exists"); } VirtualMachineRelocateSpec rel = new VirtualMachineRelocateSpec(); if(linkedClone){ rel.setDiskMoveType("createNewChildDiskBacking"); }else{ rel.setDiskMoveType("moveAllDiskBackingsAndDisallowSharing"); } ClusterComputeResource clusterResource = getClusterByName(cluster); rel.setPool(getResourcePoolByName(resourcePool, clusterResource).getMOR()); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(rel); cloneSpec.setTemplate(false); - if (datastoreName != null && !datastoreName.isEmpty()) { - rel.setDatastore(getDatastoreByName(datastoreName, clusterResource).getMOR()); - } + if (datastoreName != null && !datastoreName.isEmpty()) { + Datastore datastore = getDatastoreByName(datastoreName, clusterResource); + if (datastore==null){ + System.out.println("Datastore not found!"); + throw new VSphereException("Datastore not found!"); + } + rel.setDatastore(datastore.getMOR()); + } //TODO add config to allow state of VM or snapshot if(sourceVm.getCurrentSnapShot()==null){ throw new VSphereException("Source VM or Template \"" + sourceName + "\" requires at least one snapshot!"); } cloneSpec.setSnapshot(sourceVm.getCurrentSnapShot().getMOR()); Task task = sourceVm.cloneVM_Task((Folder) sourceVm.getParent(), cloneName, cloneSpec); System.out.println("Cloning VM. Please wait ..."); String status = task.waitForTask(); if(status==TaskInfoState.success.toString()) { return; } }catch(Exception e){ throw new VSphereException(e); } throw new VSphereException("Couldn't clone \""+ sourceName +"\"! Does \""+cloneName+"\" already exist?"); } public void reconfigureVm(String name, VirtualMachineConfigSpec spec) throws VSphereException { VirtualMachine vm = getVmByName(name); if(vm==null) { throw new VSphereException("No VM or template " + name + " found"); } System.out.println("Reconfiguring VM. Please wait ..."); try { Task task = vm.reconfigVM_Task(spec); String status = task.waitForTask(); if(status.equals(TaskInfoState.success.toString())) { return; } } catch(Exception e){ throw new VSphereException("VM cannot be reconfigured:" + e.getMessage(), e); } throw new VSphereException("Couldn't reconfigure \""+ name +"\"!"); } /** * @param name - Name of VM to start * @throws VSphereException */ public void startVm(String name) throws VSphereException { try{ VirtualMachine vm = getVmByName(name); if(isPoweredOn(vm)) return; if(vm.getConfig().template) throw new VSphereException("VM represents a template!"); Task task = vm.powerOnVM_Task(null); for (int i=0, j=12; i<j; i++){ if(task.getTaskInfo().getState()==TaskInfoState.success){ System.out.println("VM was powered up successfully."); return; } if (task.getTaskInfo().getState()==TaskInfoState.running || task.getTaskInfo().getState()==TaskInfoState.queued){ Thread.sleep(5000); } //Check for copied/moved question VirtualMachineQuestionInfo q = vm.getRuntime().getQuestion(); if(q!=null && q.getId().equals("_vmx1")){ vm.answerVM(q.getId(), q.getChoice().getDefaultIndex().toString()); return; } } }catch(Exception e){ throw new VSphereException("VM cannot be started:", e); } throw new VSphereException("VM cannot be started"); } private ManagedObjectReference findSnapshotInTree( VirtualMachineSnapshotTree[] snapTree, String snapName) { for (VirtualMachineSnapshotTree node : snapTree) { if (snapName.equals(node.getName())) { return node.getSnapshot(); } else { VirtualMachineSnapshotTree[] childTree = node.getChildSnapshotList(); if (childTree != null) { ManagedObjectReference mor = findSnapshotInTree( childTree, snapName); if (mor != null) { return mor; } } } } return null; } public VirtualMachineSnapshot getSnapshotInTree( VirtualMachine vm, String snapName) { if (vm == null || snapName == null) { return null; } VirtualMachineSnapshotInfo info = vm.getSnapshot(); if (info != null) { VirtualMachineSnapshotTree[] snapTree = info.getRootSnapshotList(); if (snapTree != null) { ManagedObjectReference mor = findSnapshotInTree( snapTree, snapName); if (mor != null) { return new VirtualMachineSnapshot( vm.getServerConnection(), mor); } } } return null; } public void revertToSnapshot(String vmName, String snapName) throws VSphereException{ VirtualMachine vm = getVmByName(vmName); VirtualMachineSnapshot snap = getSnapshotInTree(vm, snapName); if (snap == null) { throw new VSphereException("Virtual Machine snapshot cannot be found"); } try{ Task task = snap.revertToSnapshot_Task(null); if (!task.waitForTask().equals(Task.SUCCESS)) { throw new VSphereException("Could not revert to snapshot"); } }catch(Exception e){ throw new VSphereException(e); } } public void deleteSnapshot(String vmName, String snapName, boolean consolidate, boolean failOnNoExist) throws VSphereException{ VirtualMachine vm = getVmByName(vmName); VirtualMachineSnapshot snap = getSnapshotInTree(vm, snapName); if (snap == null && failOnNoExist) { throw new VSphereException("Virtual Machine snapshot cannot be found"); } try{ Task task; if (snap!=null){ //Does not delete subtree; Implicitly consolidates disk task = snap.removeSnapshot_Task(false); if (!task.waitForTask().equals(Task.SUCCESS)) { throw new VSphereException("Could not delete snapshot"); } } if(!consolidate) return; //This might be redundant, but I think it consolidates all disks, //where as the removeSnapshot only consolidates the individual disk task = vm.consolidateVMDisks_Task(); if (!task.waitForTask().equals(Task.SUCCESS)) { throw new VSphereException("Could not consolidate VM disks"); } }catch(Exception e){ throw new VSphereException(e); } } public void takeSnapshot(String vmName, String snapshot, String description, boolean snapMemory) throws VSphereException{ try { Task task = getVmByName(vmName).createSnapshot_Task(snapshot, description, snapMemory, !snapMemory); if (task.waitForTask()==Task.SUCCESS) { return; } } catch (Exception e) { throw new VSphereException("Could not take snapshot", e); } throw new VSphereException("Could not take snapshot"); } public void markAsTemplate(String vmName, String snapName, boolean force) throws VSphereException { try{ VirtualMachine vm = getVmByName(vmName); if(vm.getConfig().template) return; if(isPoweredOff(vm) || force){ powerOffVm(vm, force, false); vm.markAsTemplate(); return; } }catch(Exception e){ throw new VSphereException("Could not convert to Template", e); } throw new VSphereException("Could not mark as Template. Check it's power state or select \"force.\""); } public void markAsVm(String name, String resourcePool, String cluster) throws VSphereException{ try{ VirtualMachine vm = getVmByName(name); if(vm.getConfig().template){ vm.markAsVirtualMachine( getResourcePoolByName(resourcePool, getClusterByName(cluster)), null ); } }catch(Exception e){ throw new VSphereException("Could not convert to VM", e); } } /** * Shortcut * * @param vm - VirtualMachine name of which IP is returned * @return - String containing IP address * @throws VSphereException */ public String getIp(VirtualMachine vm, int timeout) throws VSphereException { if (vm==null) throw new VSphereException("VM is null"); //Determine how many attempts will be made to fetch the IP address final int waitSeconds = 5; final int maxTries; if (timeout<=waitSeconds) maxTries = 1; else maxTries = (int) Math.round((double)timeout / waitSeconds); for(int count=0; count<maxTries; count++){ //get IP if(vm.getGuest().getIpAddress()!=null){ return vm.getGuest().getIpAddress(); } try { //wait Thread.sleep(waitSeconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } return null; } /** * @param vmName - name of VM object to retrieve * @return - VirtualMachine object * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws MalformedURLException * @throws VSphereException */ public VirtualMachine getVmByName(String vmName) throws VSphereException { try { return (VirtualMachine) new InventoryNavigator( getServiceInstance().getRootFolder()).searchManagedEntity( "VirtualMachine", vmName); } catch (Exception e) { throw new VSphereException(e); } } private Datastore getDatastoreByName(final String datastoreName, ManagedEntity rootEntity) throws RemoteException, MalformedURLException { if (rootEntity==null) rootEntity=getServiceInstance().getRootFolder(); return (Datastore) new InventoryNavigator(rootEntity).searchManagedEntity("Datastore", datastoreName); } /** * @param poolName - Name of pool to use * @return - ResourcePool obect * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws MalformedURLException * @throws VSphereException */ private ResourcePool getResourcePoolByName(final String poolName, ManagedEntity rootEntity) throws InvalidProperty, RuntimeFault, RemoteException, MalformedURLException { if (rootEntity==null) rootEntity=getServiceInstance().getRootFolder(); return (ResourcePool) new InventoryNavigator( rootEntity).searchManagedEntity( "ResourcePool", poolName); } /** * @param clusterName - Name of cluster name to find * @param rootEntity - managed entity to search * @return - ClusterComputeResource object * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws MalformedURLException * @throws VSphereException */ private ClusterComputeResource getClusterByName(final String clusterName, ManagedEntity rootEntity) throws InvalidProperty, RuntimeFault, RemoteException, MalformedURLException { if (rootEntity==null) rootEntity=getServiceInstance().getRootFolder(); return (ClusterComputeResource) new InventoryNavigator( rootEntity).searchManagedEntity( "ClusterComputeResource", clusterName); } /** * @param clusterName - Name of cluster name to find * @return - ClusterComputeResource object * @throws InvalidProperty * @throws RuntimeFault * @throws RemoteException * @throws MalformedURLException * @throws VSphereException */ private ClusterComputeResource getClusterByName(final String clusterName) throws InvalidProperty, RuntimeFault, RemoteException, MalformedURLException { return getClusterByName(clusterName, null); } /** * Detroys the VM in vSphere * @param name - VM object to destroy * @throws VSphereException */ public void destroyVm(String name, boolean failOnNoExist) throws VSphereException{ try{ VirtualMachine vm = getVmByName(name); if(vm==null){ if(failOnNoExist) throw new VSphereException("VM does not exist"); System.out.println("VM does not exist, or already deleted!"); return; } if(!vm.getConfig().template) { powerOffVm(vm, true, false); } String status = vm.destroy_Task().waitForTask(); if(status==Task.SUCCESS) { System.out.println("VM was deleted successfully."); return; } }catch(Exception e){ throw new VSphereException(e.getMessage()); } throw new VSphereException("Could not delete VM!"); } /** * Renames a VM Snapshot * @param oldName the current name of the vm * @param newName the new name of the vm * @param newDescription the new description of the vm * @throws VSphereException */ public void renameVmSnapshot(String vmName, String oldName, String newName, String newDescription) throws VSphereException{ try{ VirtualMachine vm = getVmByName(vmName); if(vm==null){ throw new VSphereException("VM does not exist"); } VirtualMachineSnapshot snapshot = getSnapshotInTree(vm, oldName); snapshot.renameSnapshot(newName, newDescription); System.out.println("VM Snapshot was renamed successfully."); return; }catch(Exception e){ throw new VSphereException(e.getMessage()); } } /** * Renames the VM vSphere * @param oldName the current name of the vm * @param newName the new name of the vm * @throws VSphereException */ public void renameVm(String oldName, String newName) throws VSphereException{ try{ VirtualMachine vm = getVmByName(oldName); if(vm==null){ throw new VSphereException("VM does not exist"); } String status = vm.rename_Task(newName).waitForTask(); if(status.equals(Task.SUCCESS)) { System.out.println("VM was renamed successfully."); return; } }catch(Exception e){ throw new VSphereException(e.getMessage()); } throw new VSphereException("Could not rename VM!"); } private boolean isSuspended(VirtualMachine vm){ return (vm.getRuntime().getPowerState() == VirtualMachinePowerState.suspended); } private boolean isPoweredOn(VirtualMachine vm){ return (vm.getRuntime().getPowerState() == VirtualMachinePowerState.poweredOn); } private boolean isPoweredOff(VirtualMachine vm){ return (vm.getRuntime().getPowerState() == VirtualMachinePowerState.poweredOff); } public boolean vmToolIsEnabled(VirtualMachine vm) { VirtualMachineToolsStatus status = vm.getGuest().toolsStatus; return ((status == VirtualMachineToolsStatus.toolsOk) || (status == VirtualMachineToolsStatus.toolsOld)); } public void powerOffVm(VirtualMachine vm, boolean evenIfSuspended, boolean shutdownGracefully) throws VSphereException{ if(vm.getConfig().template) throw new VSphereException("VM represents a template!"); if (isPoweredOn(vm) || (evenIfSuspended && isSuspended(vm))) { boolean doHardShutdown = true; String status; try { if (!isSuspended(vm) && shutdownGracefully && vmToolIsEnabled(vm)) { System.out.println("Requesting guest shutdown"); vm.shutdownGuest(); // Wait for up to 180 seconds for a shutdown - then shutdown hard. for (int i = 0; i <= 180; i++) { Thread.sleep(1000); if (isPoweredOff(vm)) { doHardShutdown = false; System.out.println("VM gracefully powered down successfully."); return; } } } if (doHardShutdown) { System.out.println("Powering off the VM"); status = vm.powerOffVM_Task().waitForTask(); if(status==Task.SUCCESS) { System.out.println("VM was powered down successfully."); return; } } } catch (Exception e) { throw new VSphereException(e); } } else if (isPoweredOff(vm)){ System.out.println("Machine is already off."); return; } throw new VSphereException("Machine could not be powered down!"); } public void suspendVm(VirtualMachine vm) throws VSphereException{ if (isPoweredOn(vm)) { String status; try { //TODO is this better? //vm.shutdownGuest() status = vm.suspendVM_Task().waitForTask(); } catch (Exception e) { throw new VSphereException(e); } if(status==Task.SUCCESS) { System.out.println("VM was suspended successfully."); return; } } else { System.out.println("Machine not powered on."); return; } throw new VSphereException("Machine could not be suspended!"); } }
true
true
public void cloneVm(String cloneName, String sourceName, boolean linkedClone, String resourcePool, String cluster, String datastoreName) throws VSphereException { System.out.println("Creating a shallow clone of \""+ sourceName + "\" to \""+cloneName+"\""); try{ VirtualMachine sourceVm = getVmByName(sourceName); if(sourceVm==null) { throw new VSphereException("No VM or template " + sourceName + " found"); } if(getVmByName(cloneName)!=null){ throw new VSphereException("VM " + cloneName + " already exists"); } VirtualMachineRelocateSpec rel = new VirtualMachineRelocateSpec(); if(linkedClone){ rel.setDiskMoveType("createNewChildDiskBacking"); }else{ rel.setDiskMoveType("moveAllDiskBackingsAndDisallowSharing"); } ClusterComputeResource clusterResource = getClusterByName(cluster); rel.setPool(getResourcePoolByName(resourcePool, clusterResource).getMOR()); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(rel); cloneSpec.setTemplate(false); if (datastoreName != null && !datastoreName.isEmpty()) { rel.setDatastore(getDatastoreByName(datastoreName, clusterResource).getMOR()); } //TODO add config to allow state of VM or snapshot if(sourceVm.getCurrentSnapShot()==null){ throw new VSphereException("Source VM or Template \"" + sourceName + "\" requires at least one snapshot!"); } cloneSpec.setSnapshot(sourceVm.getCurrentSnapShot().getMOR()); Task task = sourceVm.cloneVM_Task((Folder) sourceVm.getParent(), cloneName, cloneSpec); System.out.println("Cloning VM. Please wait ..."); String status = task.waitForTask(); if(status==TaskInfoState.success.toString()) { return; } }catch(Exception e){ throw new VSphereException(e); } throw new VSphereException("Couldn't clone \""+ sourceName +"\"! Does \""+cloneName+"\" already exist?"); }
public void cloneVm(String cloneName, String sourceName, boolean linkedClone, String resourcePool, String cluster, String datastoreName) throws VSphereException { System.out.println("Creating a shallow clone of \""+ sourceName + "\" to \""+cloneName+"\""); try{ VirtualMachine sourceVm = getVmByName(sourceName); if(sourceVm==null) { throw new VSphereException("No VM or template " + sourceName + " found"); } if(getVmByName(cloneName)!=null){ throw new VSphereException("VM " + cloneName + " already exists"); } VirtualMachineRelocateSpec rel = new VirtualMachineRelocateSpec(); if(linkedClone){ rel.setDiskMoveType("createNewChildDiskBacking"); }else{ rel.setDiskMoveType("moveAllDiskBackingsAndDisallowSharing"); } ClusterComputeResource clusterResource = getClusterByName(cluster); rel.setPool(getResourcePoolByName(resourcePool, clusterResource).getMOR()); VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec(); cloneSpec.setLocation(rel); cloneSpec.setTemplate(false); if (datastoreName != null && !datastoreName.isEmpty()) { Datastore datastore = getDatastoreByName(datastoreName, clusterResource); if (datastore==null){ System.out.println("Datastore not found!"); throw new VSphereException("Datastore not found!"); } rel.setDatastore(datastore.getMOR()); } //TODO add config to allow state of VM or snapshot if(sourceVm.getCurrentSnapShot()==null){ throw new VSphereException("Source VM or Template \"" + sourceName + "\" requires at least one snapshot!"); } cloneSpec.setSnapshot(sourceVm.getCurrentSnapShot().getMOR()); Task task = sourceVm.cloneVM_Task((Folder) sourceVm.getParent(), cloneName, cloneSpec); System.out.println("Cloning VM. Please wait ..."); String status = task.waitForTask(); if(status==TaskInfoState.success.toString()) { return; } }catch(Exception e){ throw new VSphereException(e); } throw new VSphereException("Couldn't clone \""+ sourceName +"\"! Does \""+cloneName+"\" already exist?"); }
diff --git a/src/radlab/rain/Generator.java b/src/radlab/rain/Generator.java index e974518..aaf1899 100644 --- a/src/radlab/rain/Generator.java +++ b/src/radlab/rain/Generator.java @@ -1,96 +1,96 @@ /* * Copyright (c) 2010, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package radlab.rain; import org.json.JSONObject; import org.json.JSONException; /** * The Generator abstract class provides a default constructor, required * properties, and specifies the methods that must be implemented in order * to interface with the benchmark architecture.<br /> * <br /> * The basic Generator has a name, associates itself with a scenario track, * and keeps a reference to a scoreboard in which operation results are * dropped off. */ public abstract class Generator { /** A name with which to identify this generator (e.g. for logging). */ protected String _name = ""; /** The scenario track that identifies the load profile. */ protected ScenarioTrack _loadTrack = null; /** The think time and cycle time */ protected long _thinkTime = 0; protected long _cycleTime = 0; /** A reference to the scoreboard to drop results off at. */ protected IScoreboard _scoreboard = null; /** A reference to the latest load profile used */ protected LoadProfile _latestLoadProfile = null; public String getName() { return this._name; } public void setName( String val ) { this._name = val; } public ScenarioTrack getTrack() { return this._loadTrack; } public void setScoreboard( IScoreboard scoreboard ) { this._scoreboard = scoreboard; } public IScoreboard getScoreboard() { return this._scoreboard; } public void setLatestLoadProfile( LoadProfile val ) { this._latestLoadProfile = val; } public LoadProfile getLatestLoadProfile() { return this._latestLoadProfile; } /** * Creates a new Generator. * * @param track The track configuration with which to run this generator. */ public Generator( ScenarioTrack track ) { this._loadTrack = track; - this.initialize(); + //this.initialize(); // let the Benchmark call initialize } public abstract long getThinkTime(); public void setMeanThinkTime( long val ){ this._thinkTime = val; } public abstract long getCycleTime(); public void setMeanCycleTime( long val ) { this._cycleTime = val; } public abstract Operation nextRequest( int lastOperation ); public abstract void initialize(); public abstract void dispose(); // Method for configuring the driver prior to its initialization public void configure( JSONObject config ) throws JSONException {} }
true
true
public Generator( ScenarioTrack track ) { this._loadTrack = track; this.initialize(); }
public Generator( ScenarioTrack track ) { this._loadTrack = track; //this.initialize(); // let the Benchmark call initialize }
diff --git a/alchemy-core/src/alchemy/libs/LibCore4.java b/alchemy-core/src/alchemy/libs/LibCore4.java index db33d7e..5a6e440 100644 --- a/alchemy-core/src/alchemy/libs/LibCore4.java +++ b/alchemy-core/src/alchemy/libs/LibCore4.java @@ -1,791 +1,795 @@ /* * This file is a part of Alchemy OS project. * Copyright (C) 2011-2014, Sergey Basalaev <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package alchemy.libs; import alchemy.evm.EtherLoader; import alchemy.fs.Filesystem; import alchemy.io.ConnectionInputStream; import alchemy.io.ConnectionOutputStream; import alchemy.io.IO; import alchemy.io.Pipe; import alchemy.io.TerminalInput; import alchemy.platform.Platform; import alchemy.system.AlchemyException; import alchemy.system.Function; import alchemy.system.Library; import alchemy.system.NativeLibrary; import alchemy.system.Process; import alchemy.system.ProcessThread; import alchemy.types.Int32; import alchemy.util.ArrayList; import alchemy.util.Arrays; import alchemy.util.HashMap; import alchemy.util.Lock; import alchemy.util.PartiallyAppliedFunction; import alchemy.util.Strings; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.Random; import javax.microedition.io.Connection; import javax.microedition.io.StreamConnection; /** * Core runtime library for Alchemy OS. * * @author Sergey Basalaev * @version 4.0 */ public final class LibCore4 extends NativeLibrary { public LibCore4() throws IOException { load("/symbols/core4"); name = "libcore.4.so"; } protected Object invokeNative(int index, Process p, Object[] args) throws Exception { switch (index) { /* == Header: builtin.eh == */ case 0: // acopy(src: Array, sofs: Int, dest: Array, dofs: Int, len: Int) Arrays.arrayCopy(args[0], ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 1: // Function.apply(args: [Any]): Function return new PartiallyAppliedFunction((Function)args[0], (Object[])args[1]); case 2: // throw(code: Int = FAIL, msg: String = null) throw new AlchemyException(ival(args[0]), (String)args[1]); /* == Header: string.eh == */ case 3: // Any.tostr(): String return Strings.toString(args[0]); case 4: // Char.tostr(): String return String.valueOf((char)ival(args[0])); case 5: // Int.tobin():String return Integer.toBinaryString(ival(args[0])); case 6: // Int.tooct():String return Integer.toOctalString(ival(args[0])); case 7: // Int.tohex():String return Integer.toHexString(ival(args[0])); case 8: // Int.tobase(base: Int): String return Integer.toString(ival(args[0]), ival(args[1])); case 9: // Long.tobase(base: Int): String return Long.toString(lval(args[0]), ival(args[1])); case 10: // String.tointbase(base: Int): Int return Ival(Integer.parseInt((String)args[0], ival(args[1]))); case 11: // String.tolongbase(base: Int): Long return Lval(Long.parseLong((String)args[0], ival(args[1]))); case 12: // String.tofloat(): Float return Fval(Float.parseFloat((String)args[0])); case 13: // String.todouble(): Double return Dval(Double.parseDouble((String)args[0])); case 14: { // String.get(at: Int): Char String str = (String)args[0]; int at = ival(args[1]); if (at < 0) at += str.length(); return Ival(str.charAt(at)); } case 15: // String.len(): Int return Ival(((String)args[0]).length()); case 16: { // String.range(from: Int, to: Int): String String str = (String) args[0]; int from = ival(args[1]); int to = ival(args[2]); if (from < 0) from += str.length(); if (to < 0) to += str.length(); return str.substring(from, to); } case 17: { // String.indexof(ch: Char, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf(ival(args[1]), from)); } case 18: // String.lindexof(ch: Char): Int return Ival(((String)args[0]).lastIndexOf(ival(args[1]))); case 19: { // String.find(sub: String, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf((String)args[1], from)); } case 20: // String.ucase(): String return ((String)args[0]).toUpperCase(); case 21: // String.lcase(): String return ((String)args[0]).toLowerCase(); case 22: // String.concat(str: String): String return ((String)args[0]).concat((String)args[1]); case 23: // String.cmp(str: String): Int return Ival(((String)args[0]).compareTo((String)args[1])); case 24: // String.trim(): String return ((String)args[0]).trim(); case 25: // String.split(ch: Char, skipEmpty: Bool = false): [String] return Strings.split((String)args[0], (char)ival(args[1]), bval(args[2])); case 26: // String.format(args: [Any]): String return Strings.format((String)args[0], (Object[])args[1]); case 27: // String.chars(): [Char] return ((String)args[0]).toCharArray(); case 28: // String.utfbytes(): [Byte] return Strings.utfEncode((String)args[0]); case 29: { // String.startswith(prefix: String, from: Int = 0): Bool String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.startsWith((String)args[1], from)); } case 30: // String.replace(oldch: Char, newch: Char): String return ((String)args[0]).replace((char)ival(args[1]), (char)ival(args[2])); case 31: // String.hash(): Int return Ival(((String)args[0]).hashCode()); case 32: // ca2str(ca: [Char]): String return new String((char[])args[0]); case 33: // ba2utf(ba: [Byte]): String return Strings.utfDecode((byte[])args[0]); /* == Header: error.eh == */ case 34: // Error.code(): Int return Ival(((AlchemyException)args[0]).errcode); case 35: // Error.msg(): String return ((AlchemyException)args[0]).getMessage(); case 36: // Error.traceLen(): Int return Ival(((AlchemyException)args[0]).getTraceLength()); case 37: // Error.traceName(index: Int): String return ((AlchemyException)args[0]).getTraceElementName(ival(args[1])); case 38: // Error.traceDbg(index: Int): String return ((AlchemyException)args[0]).getTraceElementInfo(ival(args[1])); /* == Header: math.eh == */ case 39: // abs(val: Double): Double return Dval(Math.abs(dval(args[0]))); case 40: // sin(val: Double): Double return Dval(Math.sin(dval(args[0]))); case 41: // cos(val: Double): Double return Dval(Math.cos(dval(args[0]))); case 42: // tan(val: Double): Double return Dval(Math.tan(dval(args[0]))); case 43: // sqrt(val: Double): Double return Dval(Math.sqrt(dval(args[0]))); case 44: // ipow(val: Double, pow: Int): Double return Dval(alchemy.util.Math.ipow(dval(args[0]), ival(args[1]))); case 45: // exp(val: Double): Double return Dval(alchemy.util.Math.exp(dval(args[0]))); case 46: // log(val: Double): Double return Dval(alchemy.util.Math.log(dval(args[0]))); case 47: // asin(val: Double): Double return Dval(alchemy.util.Math.asin(dval(args[0]))); case 48: // acos(val: Double): Double return Dval(alchemy.util.Math.acos(dval(args[0]))); case 49: // atan(val: Double): Double return Dval(alchemy.util.Math.atan(dval(args[0]))); case 50: // ibits2f(bits: Int): Float return Fval(Float.intBitsToFloat(ival(args[0]))); case 51: // f2ibits(f: Float): Int return Ival(Float.floatToIntBits(fval(args[0]))); case 52: // lbits2d(bits: Long): Double return Dval(Double.longBitsToDouble(lval(args[0]))); case 53: // d2lbits(d: Double): Long return Lval(Double.doubleToLongBits(dval(args[0]))); /* == Header: rnd.eh == */ case 54: // Random.new(seed: Long) return new Random(lval(args[0])); case 55: // Random.next(n: Int): Int return Ival(((Random)args[0]).nextInt(ival(args[1]))); case 56: // Random.nextInt(): Int return Ival(((Random)args[0]).nextInt()); case 57: // Random.nextLong(): Long return Lval(((Random)args[0]).nextLong()); case 58: // Random.nextFloat(): Float return Fval(((Random)args[0]).nextFloat()); case 59: // Random.nextDouble(): Double return Dval(((Random)args[0]).nextDouble()); case 60: // Random.setSeed(seed: Long) ((Random)args[0]).setSeed(lval(args[1])); return null; /* == Header: io.eh == */ case 61: { // Connection.close() Connection conn = (Connection) args[0]; conn.close(); p.removeConnection(conn); return null; } case 62: { // StreamConnection.openInput(): IStream ConnectionInputStream in = new ConnectionInputStream(((StreamConnection)args[0]).openInputStream()); p.addConnection(in); return in; } case 63: { // StreamConnection.openOutput(): OStream ConnectionOutputStream out = new ConnectionOutputStream(((StreamConnection)args[0]).openOutputStream()); p.addConnection(out); return out; } case 64: // IStream.read(): Int return Ival(((InputStream)args[0]).read()); case 65: { // IStream.readArray(buf: [Byte], ofs: Int = 0, len: Int = -1): Int byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; return Ival(((InputStream)args[0]).read(buf, ival(args[2]), len)); } case 66: // IStream.readFully(): [Byte] return IO.readFully((InputStream)args[0]); case 67: // IStream.skip(num: Long): Long return Lval(((InputStream)args[0]).skip(lval(args[1]))); case 68: // IStream.available(): Int return Ival(((InputStream)args[0]).available()); case 69: // IStream.reset() ((InputStream)args[0]).reset(); return null; case 70: // OStream.write(b: Int) ((OutputStream)args[0]).write(ival(args[1])); return null; case 71: { // OStream.writeArray(buf: [Byte], ofs: Int, len: Int) byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; ((OutputStream)args[0]).write(buf, ival(args[2]), len); return null; } case 72: // OStream.print(a: Any) IO.print((OutputStream)args[0], args[1]); return null; case 73: // OStream.println(a: Any) IO.println((OutputStream)args[0], args[1]); return null; case 74: // OStream.flush() ((OutputStream)args[0]).flush(); return null; case 75: // OStream.writeAll(input: IStream) IO.writeAll((InputStream)args[1], (OutputStream)args[0]); return null; case 76: // stdin(): IStream return p.stdin; case 77: // stdout(): OStream return p.stdout; case 78: // stderr(): OStream return p.stderr; case 79: // setin(in: IStream) p.stdin = ((InputStream)args[0]); return null; case 80: // setout(out: OStream) p.stdout = ((OutputStream)args[0]); return null; case 81: // seterr(err: OStream) p.stderr = ((OutputStream)args[0]); return null; case 82: // pathfile(path: String): String return Filesystem.fileName((String)args[0]); case 83: // pathdir(path: String): String return Filesystem.fileParent((String)args[0]); case 84: // abspath(path: String): String return p.toFile((String)args[0]); case 85: // relpath(path: String): String return Filesystem.relativePath(p.getCurrentDirectory(), p.toFile((String)args[0])); case 86: // fcreate(path: String) Filesystem.create(p.toFile((String)args[0])); return null; case 87: // fremove(path: String) Filesystem.remove(p.toFile((String)args[0])); return null; case 88: // fremoveTree(path: String) Filesystem.removeTree(p.toFile((String)args[0])); return null; case 89: // mkdir(path: String) Filesystem.mkdir(p.toFile((String)args[0])); return null; case 90: // mkdirTree(path: String) Filesystem.mkdirTree(p.toFile((String)args[0])); return null; case 91: // fcopy(source: String, dest: String) Filesystem.copy(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 92: // fmove(source: String, dest: String) Filesystem.move(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 93: // exists(path: String): Bool return Ival(Filesystem.exists(p.toFile((String)args[0]))); case 94: // isDir(path: String): Bool return Ival(Filesystem.isDirectory(p.toFile((String)args[0]))); case 95: { // fread(path: String): IStream ConnectionInputStream input = new ConnectionInputStream(Filesystem.read(p.toFile((String)args[0]))); p.addConnection(input); return input; } case 96: { // fwrite(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.write(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 97: { // fappend(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.append(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 98: // flist(path: String): [String] return Filesystem.list(p.toFile((String)args[0])); case 99: // fmodified(path: String): Long return Lval(Filesystem.lastModified(p.toFile((String)args[0]))); case 100: // fsize(path: String): Long return Lval(Filesystem.size(p.toFile((String)args[0]))); case 101: // setRead(path: String, on: Bool) Filesystem.setRead(p.toFile((String)args[0]), bval(args[1])); return null; case 102: // setWrite(path: String, on: Bool) Filesystem.setWrite(p.toFile((String)args[0]), bval(args[1])); return null; case 103: // setExec(path: String, on: Bool) Filesystem.setExec(p.toFile((String)args[0]), bval(args[1])); return null; case 104: // canRead(path: String): Bool return Ival(Filesystem.canRead(p.toFile((String)args[0]))); case 105: // canWrite(path: String): Bool return Ival(Filesystem.canWrite(p.toFile((String)args[0]))); case 106: // canExec(path: String): Bool return Ival(Filesystem.canExec(p.toFile((String)args[0]))); case 107: // getCwd(): String return p.getCurrentDirectory(); case 108: // setCwd(dir: String) p.setCurrentDirectory(p.toFile((String)args[0])); return null; case 109: // spaceTotal(root: String): Long return Lval(Filesystem.spaceTotal(p.toFile((String)args[0]))); case 110: // spaceFree(root: String): Long return Lval(Filesystem.spaceFree(p.toFile((String)args[0]))); case 111: // spaceUsed(root: String): Long return Lval(Filesystem.spaceUsed(p.toFile((String)args[0]))); case 112: { // readUrl(url: String): IStream return IO.readUrl((String)args[0]); } case 113: // matchesGlob(path: String, glob: String): Bool return Ival(IO.matchesPattern((String)args[0], (String)args[1])); /* == Header: bufferio.eh == */ case 114: // BufferIStream.new(buf: [Byte]) return new ConnectionInputStream(new ByteArrayInputStream((byte[])args[0])); case 115: // BufferOStream.new() return new ConnectionOutputStream(new ByteArrayOutputStream()); case 116: // BufferOStream.len(): Int return Ival(((ByteArrayOutputStream)args[0]).size()); case 117: // BufferOStream.getBytes(): [Byte] return ((ByteArrayOutputStream)args[0]).toByteArray(); case 118: // BufferOStream.reset() ((ByteArrayOutputStream)args[0]).reset(); return null; /* == Header: pipe.eh == */ case 119: { // Pipe.new() Pipe pipe = new Pipe(); p.addConnection(pipe); return pipe; } /* == Header: strbuf.eh == */ case 120: // StrBuf.new(): StrBuf return new StringBuffer(); case 121: // StrBuf.get(at: Int): Char return Ival(((StringBuffer)args[0]).charAt(ival(args[1]))); case 122: // StrBuf.chars(from: Int, to: Int, buf: [Char], ofs: Int) ((StringBuffer)args[0]).getChars(ival(args[1]), ival(args[2]), (char[])args[3], ival(args[4])); return null; case 123: // StrBuf.append(a: Any): StrBuf return ((StringBuffer)args[0]).append(Strings.toString(args[1])); case 124: // StrBuf.addch(ch: Char): StrBuf return ((StringBuffer)args[0]).append((char)ival(args[1])); case 125: // StrBuf.insert(at: Int, a: Any): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), Strings.toString(args[2])); case 126: // StrBuf.insch(at: Int, ch: Char): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), (char)ival(args[2])); case 127: // StrBuf.setch(at: Int, ch: Char): StrBuf ((StringBuffer)args[0]).setCharAt(ival(args[1]), (char)ival(args[2])); return args[0]; case 128: // StrBuf.delete(from: Int, to: Int): StrBuf return ((StringBuffer)args[0]).delete(ival(args[1]), ival(args[2])); case 129: // StrBuf.delch(at: Int): StrBuf return ((StringBuffer)args[0]).deleteCharAt(ival(args[1])); case 130: // StrBuf.len(): Int return Ival(((StringBuffer)args[0]).length()); /* == Header: dl.eh == */ case 131: // loadlibrary(libname: String): Library return p.loadLibrary((String)args[0]); case 132: { // buildlibrary(in: IStream): Library InputStream in = (InputStream)args[0]; if (((in.read() << 8) | in.read()) != 0xC0DE) throw new InstantiationException("Not an Ether object"); return EtherLoader.load(p, in); } case 133: // Library.getFunction(sig: String): Function return ((Library)args[0]).getFunction((String)args[1]); /* == Header: time.eh == */ case 134: // datestr(time: Long): String return new Date(lval(args[0])).toString(); case 135: { // year(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.YEAR)); } case 136: { // month(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MONTH)); } case 137: { // day(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_MONTH)); } case 138: { // dow(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_WEEK)); } case 139: { // hour(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.HOUR_OF_DAY)); } case 140: { // minute(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MINUTE)); } case 141: { // second(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.SECOND)); } case 142: { // millis(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MILLISECOND)); } case 143: { // timeof(year: Int, month: Int, day: Int, hour: Int, min: Int, sec: Int, millis: Int): Long Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, ival(args[0])); cal.set(Calendar.MONTH, ival(args[1])); cal.set(Calendar.DAY_OF_MONTH, ival(args[2])); cal.set(Calendar.HOUR_OF_DAY, ival(args[3])); cal.set(Calendar.MINUTE, ival(args[4])); cal.set(Calendar.SECOND, ival(args[5])); cal.set(Calendar.MILLISECOND, ival(args[6])); return Lval(cal.getTime().getTime()); } /* == Header: dict.eh == */ case 144: // Dict.new(): Dict return new HashMap(); case 145: // Dict.len(): Int return Ival(((HashMap)args[0]).size()); case 146: // Dict.get(key: Any): Any return ((HashMap)args[0]).get(args[1]); case 147: // Dict.set(key: Any, value: Any) ((HashMap)args[0]).set(args[1], args[2]); return null; case 148: // Dict.remove(key: Any) ((HashMap)args[0]).remove(args[1]); return null; case 149: // Dict.clear() ((HashMap)args[0]).clear(); return null; case 150: // Dict.keys(): [Any] return ((HashMap)args[0]).keys(); /* == Header: list.eh == */ case 151: { // List.new(a: Array = null): List ArrayList list = new ArrayList(); if (args[0] != null) list.addFrom(args[0], 0, -1); return list; } case 152: // List.len(): Int return Ival(((ArrayList)args[0]).size()); case 153: // List.get(at: Int): Any return ((ArrayList)args[0]).get(ival(args[1])); case 154: // List.set(at: Int, val: Any) ((ArrayList)args[0]).set(ival(args[1]), args[2]); return null; case 155: // List.add(val: Any) ((ArrayList)args[0]).add(args[1]); return null; case 156: // List.addFrom(arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).addFrom(args[1], ival(args[2]), ival(args[3])); return null; case 157: // List.insert(at: Int, val: Any) ((ArrayList)args[0]).insert(ival(args[1]), args[2]); return null; case 158: // List.insertfrom(at: Int, arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).insertFrom(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 159: // List.remove(at: Int) ((ArrayList)args[0]).remove(ival(args[1])); return null; case 160: // List.clear() ((ArrayList)args[0]).clear(); return null; case 161: // List.range(from: Int, to: Int): List return ((ArrayList)args[0]).getRange(ival(args[1]), ival(args[2])); case 162: // List.indexof(val: Any, from: Int = 0): Int return Ival(((ArrayList)args[0]).indexOf(args[1], ival(args[2]))); case 163: // List.lindexof(val: Any): Int return Ival(((ArrayList)args[0]).lastIndexOf(args[1])); case 164: { // List.filter(f: (Any):Bool): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { Object e = oldlist.get(i); if (f.invoke(p, new Object[] {oldlist.get(i)}) == Int32.ONE) { newlist.add(e); } } return newlist; } case 165: { // List.filterself(f: (Any):Bool) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); int i=0; while (i < len) { if (f.invoke(p, new Object[] {list.get(i)}) == Int32.ONE) { i++; } else { list.remove(i); len--; } } return null; } case 166: { // List.map(f: (Any):Any): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { newlist.add(f.invoke(p, new Object[] {oldlist.get(i)})); } return newlist; } case 167: { // List.mapself(f: (Any):Any) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); for (int i=0; i<len; i++) { list.set(i, f.invoke(p, new Object[] {list.get(i)})); } return null; } case 168: { // List.reduce(f: (Any,Any):Any): Any ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); if (len == 0) return null; Object ret = list.get(0); Object[] fparams = new Object[2]; for (int i=1; i<len; i++) { fparams[0] = ret; fparams[1] = list.get(i); ret = f.invoke(p, fparams); } return ret; } case 169: { // List.sort(f: (Any,Any):Int): List ArrayList oldList = (ArrayList)args[0]; Object[] data = new Object[oldList.size()]; oldList.copyInto(data); - Arrays.qsort(data, 0, data.length, p, (Function)args[1]); + if (data.length > 0) { + Arrays.qsort(data, 0, data.length-1, p, (Function)args[1]); + } ArrayList newList = new ArrayList(data.length); newList.addFrom(data, 0, data.length); return newList; } case 170: { // List.sortself(f: (Any,Any):Int) ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); - Arrays.qsort(data, 0, data.length, p, (Function)args[1]); + if (data.length > 0) { + Arrays.qsort(data, 0, data.length-1, p, (Function)args[1]); + } list.clear(); list.addFrom(data, 0, data.length); return null; } case 171: { // List.reverse(): List ArrayList oldList = (ArrayList)args[0]; int len = oldList.size(); ArrayList newList = new ArrayList(len); for (int i=len-1; i>=0; i--) { newList.add(oldList.get(i)); } return newList; } case 172: { // List.toarray(): [Any] ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); return data; } case 173: // List.copyInto(from: Int, buf: Array, ofs: Int, len: Int) ((ArrayList)args[0]).copyInto(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; /* == Header: thread.eh == */ case 174: // currentThread(): Thread return Thread.currentThread(); case 175: // Thread.new(run: ()); return p.createThread((Function)args[0]); case 176: // Thread.start() ((ProcessThread)args[0]).start(); return null; case 177: // Thread.isAlive(): Bool return Ival(((ProcessThread)args[0]).isAlive()); case 178: // Thread.interrupt() ((ProcessThread)args[0]).interrupt(); return null; case 179: // Thread.isInterrupted(): Bool return Ival(((ProcessThread)args[0]).isInterrupted()); case 180: // Thread.join() ((ProcessThread)args[0]).join(); return null; case 181: // Lock.new() return new Lock(); case 182: // Lock.lock() ((Lock)args[0]).lock(); return null; case 183: // Lock.tryLock(): Bool return Ival(((Lock)args[0]).tryLock()); case 184: // Lock.unlock() ((Lock)args[0]).unlock(); return null; /* == Header: process.eh == */ case 185: // currentProcess(): Process return p; case 186: { // Process.new(cmd: String, args: [String]) Object[] objArgs = (Object[])args[1]; String[] strArgs = new String[objArgs.length]; System.arraycopy(objArgs, 0, strArgs, 0, objArgs.length); return new Process(p, (String)args[0], strArgs); } case 187: // Process.getState(): Int return Ival(((Process)args[0]).getState()); case 188: // Process.getPriority(): Int return Ival(((Process)args[0]).getPriority()); case 189: { // Process.setPriority(value: Int) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setPriority(ival(args[1])); return null; } else { throw new SecurityException(); } } case 190: // Process.getName(): String return ((Process)args[0]).getName(); case 191: // Process.getArgs(): [String] return ((Process)args[0]).getArgs(); case 192: { // Process.setEnv(key: String, value: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setEnv((String)args[1], (String)args[2]); return null; } else { throw new SecurityException(); } } case 193: { // Process.setIn(in: IStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdin = (InputStream)args[1]; return null; } else { throw new SecurityException(); } } case 194: { // Process.setOut(out: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdout = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 195: { // Process.setErr(err: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stderr = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 196: { // Process.setCwd(cwd: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setCurrentDirectory(p.toFile((String)args[1])); return null; } else { throw new SecurityException(); } } case 197: // Process.start(): Process return ((Process)args[0]).start(); case 198: // Process.waitFor(): Int return Ival(((Process)args[0]).waitFor()); case 199: // Process.kill() ((Process)args[0]).kill(); return null; case 200: // Process.getExitCode(): Int return Ival(((Process)args[0]).getExitCode()); case 201: // Process.getError(): Error return ((Process)args[0]).getError(); /* == Header: sys.eh == */ case 202: // systime(): Long return Lval(System.currentTimeMillis()); case 203: // getenv(key: String): String return p.getEnv((String)args[0]); case 204: // setenv(key: String, val: String) p.setEnv((String)args[0], (String)args[1]); return null; case 205: // sleep(millis: Int) Thread.sleep(lval(args[0])); return null; case 206: // sysProperty(str: String): String return System.getProperty((String)args[0]); case 207: // platformRequest(url: String): Bool return Ival(Platform.getPlatform().getCore().platformRequest((String)args[0])); /* == Header: term.eh == */ case 208: // isTerm(stream: IStream): Bool return Ival(args[0] instanceof TerminalInput); case 209: // TermIStream.clear() ((TerminalInput)args[0]).clear(); return null; case 210: // TermIStream.getPrompt(): String return ((TerminalInput)args[0]).getPrompt(); case 211: // TermIStream.setPrompt(prompt: String) ((TerminalInput)args[0]).setPrompt((String)args[1]); return null; default: return null; } } }
false
true
protected Object invokeNative(int index, Process p, Object[] args) throws Exception { switch (index) { /* == Header: builtin.eh == */ case 0: // acopy(src: Array, sofs: Int, dest: Array, dofs: Int, len: Int) Arrays.arrayCopy(args[0], ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 1: // Function.apply(args: [Any]): Function return new PartiallyAppliedFunction((Function)args[0], (Object[])args[1]); case 2: // throw(code: Int = FAIL, msg: String = null) throw new AlchemyException(ival(args[0]), (String)args[1]); /* == Header: string.eh == */ case 3: // Any.tostr(): String return Strings.toString(args[0]); case 4: // Char.tostr(): String return String.valueOf((char)ival(args[0])); case 5: // Int.tobin():String return Integer.toBinaryString(ival(args[0])); case 6: // Int.tooct():String return Integer.toOctalString(ival(args[0])); case 7: // Int.tohex():String return Integer.toHexString(ival(args[0])); case 8: // Int.tobase(base: Int): String return Integer.toString(ival(args[0]), ival(args[1])); case 9: // Long.tobase(base: Int): String return Long.toString(lval(args[0]), ival(args[1])); case 10: // String.tointbase(base: Int): Int return Ival(Integer.parseInt((String)args[0], ival(args[1]))); case 11: // String.tolongbase(base: Int): Long return Lval(Long.parseLong((String)args[0], ival(args[1]))); case 12: // String.tofloat(): Float return Fval(Float.parseFloat((String)args[0])); case 13: // String.todouble(): Double return Dval(Double.parseDouble((String)args[0])); case 14: { // String.get(at: Int): Char String str = (String)args[0]; int at = ival(args[1]); if (at < 0) at += str.length(); return Ival(str.charAt(at)); } case 15: // String.len(): Int return Ival(((String)args[0]).length()); case 16: { // String.range(from: Int, to: Int): String String str = (String) args[0]; int from = ival(args[1]); int to = ival(args[2]); if (from < 0) from += str.length(); if (to < 0) to += str.length(); return str.substring(from, to); } case 17: { // String.indexof(ch: Char, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf(ival(args[1]), from)); } case 18: // String.lindexof(ch: Char): Int return Ival(((String)args[0]).lastIndexOf(ival(args[1]))); case 19: { // String.find(sub: String, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf((String)args[1], from)); } case 20: // String.ucase(): String return ((String)args[0]).toUpperCase(); case 21: // String.lcase(): String return ((String)args[0]).toLowerCase(); case 22: // String.concat(str: String): String return ((String)args[0]).concat((String)args[1]); case 23: // String.cmp(str: String): Int return Ival(((String)args[0]).compareTo((String)args[1])); case 24: // String.trim(): String return ((String)args[0]).trim(); case 25: // String.split(ch: Char, skipEmpty: Bool = false): [String] return Strings.split((String)args[0], (char)ival(args[1]), bval(args[2])); case 26: // String.format(args: [Any]): String return Strings.format((String)args[0], (Object[])args[1]); case 27: // String.chars(): [Char] return ((String)args[0]).toCharArray(); case 28: // String.utfbytes(): [Byte] return Strings.utfEncode((String)args[0]); case 29: { // String.startswith(prefix: String, from: Int = 0): Bool String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.startsWith((String)args[1], from)); } case 30: // String.replace(oldch: Char, newch: Char): String return ((String)args[0]).replace((char)ival(args[1]), (char)ival(args[2])); case 31: // String.hash(): Int return Ival(((String)args[0]).hashCode()); case 32: // ca2str(ca: [Char]): String return new String((char[])args[0]); case 33: // ba2utf(ba: [Byte]): String return Strings.utfDecode((byte[])args[0]); /* == Header: error.eh == */ case 34: // Error.code(): Int return Ival(((AlchemyException)args[0]).errcode); case 35: // Error.msg(): String return ((AlchemyException)args[0]).getMessage(); case 36: // Error.traceLen(): Int return Ival(((AlchemyException)args[0]).getTraceLength()); case 37: // Error.traceName(index: Int): String return ((AlchemyException)args[0]).getTraceElementName(ival(args[1])); case 38: // Error.traceDbg(index: Int): String return ((AlchemyException)args[0]).getTraceElementInfo(ival(args[1])); /* == Header: math.eh == */ case 39: // abs(val: Double): Double return Dval(Math.abs(dval(args[0]))); case 40: // sin(val: Double): Double return Dval(Math.sin(dval(args[0]))); case 41: // cos(val: Double): Double return Dval(Math.cos(dval(args[0]))); case 42: // tan(val: Double): Double return Dval(Math.tan(dval(args[0]))); case 43: // sqrt(val: Double): Double return Dval(Math.sqrt(dval(args[0]))); case 44: // ipow(val: Double, pow: Int): Double return Dval(alchemy.util.Math.ipow(dval(args[0]), ival(args[1]))); case 45: // exp(val: Double): Double return Dval(alchemy.util.Math.exp(dval(args[0]))); case 46: // log(val: Double): Double return Dval(alchemy.util.Math.log(dval(args[0]))); case 47: // asin(val: Double): Double return Dval(alchemy.util.Math.asin(dval(args[0]))); case 48: // acos(val: Double): Double return Dval(alchemy.util.Math.acos(dval(args[0]))); case 49: // atan(val: Double): Double return Dval(alchemy.util.Math.atan(dval(args[0]))); case 50: // ibits2f(bits: Int): Float return Fval(Float.intBitsToFloat(ival(args[0]))); case 51: // f2ibits(f: Float): Int return Ival(Float.floatToIntBits(fval(args[0]))); case 52: // lbits2d(bits: Long): Double return Dval(Double.longBitsToDouble(lval(args[0]))); case 53: // d2lbits(d: Double): Long return Lval(Double.doubleToLongBits(dval(args[0]))); /* == Header: rnd.eh == */ case 54: // Random.new(seed: Long) return new Random(lval(args[0])); case 55: // Random.next(n: Int): Int return Ival(((Random)args[0]).nextInt(ival(args[1]))); case 56: // Random.nextInt(): Int return Ival(((Random)args[0]).nextInt()); case 57: // Random.nextLong(): Long return Lval(((Random)args[0]).nextLong()); case 58: // Random.nextFloat(): Float return Fval(((Random)args[0]).nextFloat()); case 59: // Random.nextDouble(): Double return Dval(((Random)args[0]).nextDouble()); case 60: // Random.setSeed(seed: Long) ((Random)args[0]).setSeed(lval(args[1])); return null; /* == Header: io.eh == */ case 61: { // Connection.close() Connection conn = (Connection) args[0]; conn.close(); p.removeConnection(conn); return null; } case 62: { // StreamConnection.openInput(): IStream ConnectionInputStream in = new ConnectionInputStream(((StreamConnection)args[0]).openInputStream()); p.addConnection(in); return in; } case 63: { // StreamConnection.openOutput(): OStream ConnectionOutputStream out = new ConnectionOutputStream(((StreamConnection)args[0]).openOutputStream()); p.addConnection(out); return out; } case 64: // IStream.read(): Int return Ival(((InputStream)args[0]).read()); case 65: { // IStream.readArray(buf: [Byte], ofs: Int = 0, len: Int = -1): Int byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; return Ival(((InputStream)args[0]).read(buf, ival(args[2]), len)); } case 66: // IStream.readFully(): [Byte] return IO.readFully((InputStream)args[0]); case 67: // IStream.skip(num: Long): Long return Lval(((InputStream)args[0]).skip(lval(args[1]))); case 68: // IStream.available(): Int return Ival(((InputStream)args[0]).available()); case 69: // IStream.reset() ((InputStream)args[0]).reset(); return null; case 70: // OStream.write(b: Int) ((OutputStream)args[0]).write(ival(args[1])); return null; case 71: { // OStream.writeArray(buf: [Byte], ofs: Int, len: Int) byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; ((OutputStream)args[0]).write(buf, ival(args[2]), len); return null; } case 72: // OStream.print(a: Any) IO.print((OutputStream)args[0], args[1]); return null; case 73: // OStream.println(a: Any) IO.println((OutputStream)args[0], args[1]); return null; case 74: // OStream.flush() ((OutputStream)args[0]).flush(); return null; case 75: // OStream.writeAll(input: IStream) IO.writeAll((InputStream)args[1], (OutputStream)args[0]); return null; case 76: // stdin(): IStream return p.stdin; case 77: // stdout(): OStream return p.stdout; case 78: // stderr(): OStream return p.stderr; case 79: // setin(in: IStream) p.stdin = ((InputStream)args[0]); return null; case 80: // setout(out: OStream) p.stdout = ((OutputStream)args[0]); return null; case 81: // seterr(err: OStream) p.stderr = ((OutputStream)args[0]); return null; case 82: // pathfile(path: String): String return Filesystem.fileName((String)args[0]); case 83: // pathdir(path: String): String return Filesystem.fileParent((String)args[0]); case 84: // abspath(path: String): String return p.toFile((String)args[0]); case 85: // relpath(path: String): String return Filesystem.relativePath(p.getCurrentDirectory(), p.toFile((String)args[0])); case 86: // fcreate(path: String) Filesystem.create(p.toFile((String)args[0])); return null; case 87: // fremove(path: String) Filesystem.remove(p.toFile((String)args[0])); return null; case 88: // fremoveTree(path: String) Filesystem.removeTree(p.toFile((String)args[0])); return null; case 89: // mkdir(path: String) Filesystem.mkdir(p.toFile((String)args[0])); return null; case 90: // mkdirTree(path: String) Filesystem.mkdirTree(p.toFile((String)args[0])); return null; case 91: // fcopy(source: String, dest: String) Filesystem.copy(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 92: // fmove(source: String, dest: String) Filesystem.move(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 93: // exists(path: String): Bool return Ival(Filesystem.exists(p.toFile((String)args[0]))); case 94: // isDir(path: String): Bool return Ival(Filesystem.isDirectory(p.toFile((String)args[0]))); case 95: { // fread(path: String): IStream ConnectionInputStream input = new ConnectionInputStream(Filesystem.read(p.toFile((String)args[0]))); p.addConnection(input); return input; } case 96: { // fwrite(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.write(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 97: { // fappend(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.append(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 98: // flist(path: String): [String] return Filesystem.list(p.toFile((String)args[0])); case 99: // fmodified(path: String): Long return Lval(Filesystem.lastModified(p.toFile((String)args[0]))); case 100: // fsize(path: String): Long return Lval(Filesystem.size(p.toFile((String)args[0]))); case 101: // setRead(path: String, on: Bool) Filesystem.setRead(p.toFile((String)args[0]), bval(args[1])); return null; case 102: // setWrite(path: String, on: Bool) Filesystem.setWrite(p.toFile((String)args[0]), bval(args[1])); return null; case 103: // setExec(path: String, on: Bool) Filesystem.setExec(p.toFile((String)args[0]), bval(args[1])); return null; case 104: // canRead(path: String): Bool return Ival(Filesystem.canRead(p.toFile((String)args[0]))); case 105: // canWrite(path: String): Bool return Ival(Filesystem.canWrite(p.toFile((String)args[0]))); case 106: // canExec(path: String): Bool return Ival(Filesystem.canExec(p.toFile((String)args[0]))); case 107: // getCwd(): String return p.getCurrentDirectory(); case 108: // setCwd(dir: String) p.setCurrentDirectory(p.toFile((String)args[0])); return null; case 109: // spaceTotal(root: String): Long return Lval(Filesystem.spaceTotal(p.toFile((String)args[0]))); case 110: // spaceFree(root: String): Long return Lval(Filesystem.spaceFree(p.toFile((String)args[0]))); case 111: // spaceUsed(root: String): Long return Lval(Filesystem.spaceUsed(p.toFile((String)args[0]))); case 112: { // readUrl(url: String): IStream return IO.readUrl((String)args[0]); } case 113: // matchesGlob(path: String, glob: String): Bool return Ival(IO.matchesPattern((String)args[0], (String)args[1])); /* == Header: bufferio.eh == */ case 114: // BufferIStream.new(buf: [Byte]) return new ConnectionInputStream(new ByteArrayInputStream((byte[])args[0])); case 115: // BufferOStream.new() return new ConnectionOutputStream(new ByteArrayOutputStream()); case 116: // BufferOStream.len(): Int return Ival(((ByteArrayOutputStream)args[0]).size()); case 117: // BufferOStream.getBytes(): [Byte] return ((ByteArrayOutputStream)args[0]).toByteArray(); case 118: // BufferOStream.reset() ((ByteArrayOutputStream)args[0]).reset(); return null; /* == Header: pipe.eh == */ case 119: { // Pipe.new() Pipe pipe = new Pipe(); p.addConnection(pipe); return pipe; } /* == Header: strbuf.eh == */ case 120: // StrBuf.new(): StrBuf return new StringBuffer(); case 121: // StrBuf.get(at: Int): Char return Ival(((StringBuffer)args[0]).charAt(ival(args[1]))); case 122: // StrBuf.chars(from: Int, to: Int, buf: [Char], ofs: Int) ((StringBuffer)args[0]).getChars(ival(args[1]), ival(args[2]), (char[])args[3], ival(args[4])); return null; case 123: // StrBuf.append(a: Any): StrBuf return ((StringBuffer)args[0]).append(Strings.toString(args[1])); case 124: // StrBuf.addch(ch: Char): StrBuf return ((StringBuffer)args[0]).append((char)ival(args[1])); case 125: // StrBuf.insert(at: Int, a: Any): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), Strings.toString(args[2])); case 126: // StrBuf.insch(at: Int, ch: Char): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), (char)ival(args[2])); case 127: // StrBuf.setch(at: Int, ch: Char): StrBuf ((StringBuffer)args[0]).setCharAt(ival(args[1]), (char)ival(args[2])); return args[0]; case 128: // StrBuf.delete(from: Int, to: Int): StrBuf return ((StringBuffer)args[0]).delete(ival(args[1]), ival(args[2])); case 129: // StrBuf.delch(at: Int): StrBuf return ((StringBuffer)args[0]).deleteCharAt(ival(args[1])); case 130: // StrBuf.len(): Int return Ival(((StringBuffer)args[0]).length()); /* == Header: dl.eh == */ case 131: // loadlibrary(libname: String): Library return p.loadLibrary((String)args[0]); case 132: { // buildlibrary(in: IStream): Library InputStream in = (InputStream)args[0]; if (((in.read() << 8) | in.read()) != 0xC0DE) throw new InstantiationException("Not an Ether object"); return EtherLoader.load(p, in); } case 133: // Library.getFunction(sig: String): Function return ((Library)args[0]).getFunction((String)args[1]); /* == Header: time.eh == */ case 134: // datestr(time: Long): String return new Date(lval(args[0])).toString(); case 135: { // year(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.YEAR)); } case 136: { // month(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MONTH)); } case 137: { // day(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_MONTH)); } case 138: { // dow(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_WEEK)); } case 139: { // hour(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.HOUR_OF_DAY)); } case 140: { // minute(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MINUTE)); } case 141: { // second(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.SECOND)); } case 142: { // millis(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MILLISECOND)); } case 143: { // timeof(year: Int, month: Int, day: Int, hour: Int, min: Int, sec: Int, millis: Int): Long Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, ival(args[0])); cal.set(Calendar.MONTH, ival(args[1])); cal.set(Calendar.DAY_OF_MONTH, ival(args[2])); cal.set(Calendar.HOUR_OF_DAY, ival(args[3])); cal.set(Calendar.MINUTE, ival(args[4])); cal.set(Calendar.SECOND, ival(args[5])); cal.set(Calendar.MILLISECOND, ival(args[6])); return Lval(cal.getTime().getTime()); } /* == Header: dict.eh == */ case 144: // Dict.new(): Dict return new HashMap(); case 145: // Dict.len(): Int return Ival(((HashMap)args[0]).size()); case 146: // Dict.get(key: Any): Any return ((HashMap)args[0]).get(args[1]); case 147: // Dict.set(key: Any, value: Any) ((HashMap)args[0]).set(args[1], args[2]); return null; case 148: // Dict.remove(key: Any) ((HashMap)args[0]).remove(args[1]); return null; case 149: // Dict.clear() ((HashMap)args[0]).clear(); return null; case 150: // Dict.keys(): [Any] return ((HashMap)args[0]).keys(); /* == Header: list.eh == */ case 151: { // List.new(a: Array = null): List ArrayList list = new ArrayList(); if (args[0] != null) list.addFrom(args[0], 0, -1); return list; } case 152: // List.len(): Int return Ival(((ArrayList)args[0]).size()); case 153: // List.get(at: Int): Any return ((ArrayList)args[0]).get(ival(args[1])); case 154: // List.set(at: Int, val: Any) ((ArrayList)args[0]).set(ival(args[1]), args[2]); return null; case 155: // List.add(val: Any) ((ArrayList)args[0]).add(args[1]); return null; case 156: // List.addFrom(arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).addFrom(args[1], ival(args[2]), ival(args[3])); return null; case 157: // List.insert(at: Int, val: Any) ((ArrayList)args[0]).insert(ival(args[1]), args[2]); return null; case 158: // List.insertfrom(at: Int, arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).insertFrom(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 159: // List.remove(at: Int) ((ArrayList)args[0]).remove(ival(args[1])); return null; case 160: // List.clear() ((ArrayList)args[0]).clear(); return null; case 161: // List.range(from: Int, to: Int): List return ((ArrayList)args[0]).getRange(ival(args[1]), ival(args[2])); case 162: // List.indexof(val: Any, from: Int = 0): Int return Ival(((ArrayList)args[0]).indexOf(args[1], ival(args[2]))); case 163: // List.lindexof(val: Any): Int return Ival(((ArrayList)args[0]).lastIndexOf(args[1])); case 164: { // List.filter(f: (Any):Bool): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { Object e = oldlist.get(i); if (f.invoke(p, new Object[] {oldlist.get(i)}) == Int32.ONE) { newlist.add(e); } } return newlist; } case 165: { // List.filterself(f: (Any):Bool) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); int i=0; while (i < len) { if (f.invoke(p, new Object[] {list.get(i)}) == Int32.ONE) { i++; } else { list.remove(i); len--; } } return null; } case 166: { // List.map(f: (Any):Any): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { newlist.add(f.invoke(p, new Object[] {oldlist.get(i)})); } return newlist; } case 167: { // List.mapself(f: (Any):Any) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); for (int i=0; i<len; i++) { list.set(i, f.invoke(p, new Object[] {list.get(i)})); } return null; } case 168: { // List.reduce(f: (Any,Any):Any): Any ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); if (len == 0) return null; Object ret = list.get(0); Object[] fparams = new Object[2]; for (int i=1; i<len; i++) { fparams[0] = ret; fparams[1] = list.get(i); ret = f.invoke(p, fparams); } return ret; } case 169: { // List.sort(f: (Any,Any):Int): List ArrayList oldList = (ArrayList)args[0]; Object[] data = new Object[oldList.size()]; oldList.copyInto(data); Arrays.qsort(data, 0, data.length, p, (Function)args[1]); ArrayList newList = new ArrayList(data.length); newList.addFrom(data, 0, data.length); return newList; } case 170: { // List.sortself(f: (Any,Any):Int) ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); Arrays.qsort(data, 0, data.length, p, (Function)args[1]); list.clear(); list.addFrom(data, 0, data.length); return null; } case 171: { // List.reverse(): List ArrayList oldList = (ArrayList)args[0]; int len = oldList.size(); ArrayList newList = new ArrayList(len); for (int i=len-1; i>=0; i--) { newList.add(oldList.get(i)); } return newList; } case 172: { // List.toarray(): [Any] ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); return data; } case 173: // List.copyInto(from: Int, buf: Array, ofs: Int, len: Int) ((ArrayList)args[0]).copyInto(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; /* == Header: thread.eh == */ case 174: // currentThread(): Thread return Thread.currentThread(); case 175: // Thread.new(run: ()); return p.createThread((Function)args[0]); case 176: // Thread.start() ((ProcessThread)args[0]).start(); return null; case 177: // Thread.isAlive(): Bool return Ival(((ProcessThread)args[0]).isAlive()); case 178: // Thread.interrupt() ((ProcessThread)args[0]).interrupt(); return null; case 179: // Thread.isInterrupted(): Bool return Ival(((ProcessThread)args[0]).isInterrupted()); case 180: // Thread.join() ((ProcessThread)args[0]).join(); return null; case 181: // Lock.new() return new Lock(); case 182: // Lock.lock() ((Lock)args[0]).lock(); return null; case 183: // Lock.tryLock(): Bool return Ival(((Lock)args[0]).tryLock()); case 184: // Lock.unlock() ((Lock)args[0]).unlock(); return null; /* == Header: process.eh == */ case 185: // currentProcess(): Process return p; case 186: { // Process.new(cmd: String, args: [String]) Object[] objArgs = (Object[])args[1]; String[] strArgs = new String[objArgs.length]; System.arraycopy(objArgs, 0, strArgs, 0, objArgs.length); return new Process(p, (String)args[0], strArgs); } case 187: // Process.getState(): Int return Ival(((Process)args[0]).getState()); case 188: // Process.getPriority(): Int return Ival(((Process)args[0]).getPriority()); case 189: { // Process.setPriority(value: Int) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setPriority(ival(args[1])); return null; } else { throw new SecurityException(); } } case 190: // Process.getName(): String return ((Process)args[0]).getName(); case 191: // Process.getArgs(): [String] return ((Process)args[0]).getArgs(); case 192: { // Process.setEnv(key: String, value: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setEnv((String)args[1], (String)args[2]); return null; } else { throw new SecurityException(); } } case 193: { // Process.setIn(in: IStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdin = (InputStream)args[1]; return null; } else { throw new SecurityException(); } } case 194: { // Process.setOut(out: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdout = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 195: { // Process.setErr(err: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stderr = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 196: { // Process.setCwd(cwd: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setCurrentDirectory(p.toFile((String)args[1])); return null; } else { throw new SecurityException(); } } case 197: // Process.start(): Process return ((Process)args[0]).start(); case 198: // Process.waitFor(): Int return Ival(((Process)args[0]).waitFor()); case 199: // Process.kill() ((Process)args[0]).kill(); return null; case 200: // Process.getExitCode(): Int return Ival(((Process)args[0]).getExitCode()); case 201: // Process.getError(): Error return ((Process)args[0]).getError(); /* == Header: sys.eh == */ case 202: // systime(): Long return Lval(System.currentTimeMillis()); case 203: // getenv(key: String): String return p.getEnv((String)args[0]); case 204: // setenv(key: String, val: String) p.setEnv((String)args[0], (String)args[1]); return null; case 205: // sleep(millis: Int) Thread.sleep(lval(args[0])); return null; case 206: // sysProperty(str: String): String return System.getProperty((String)args[0]); case 207: // platformRequest(url: String): Bool return Ival(Platform.getPlatform().getCore().platformRequest((String)args[0])); /* == Header: term.eh == */ case 208: // isTerm(stream: IStream): Bool return Ival(args[0] instanceof TerminalInput); case 209: // TermIStream.clear() ((TerminalInput)args[0]).clear(); return null; case 210: // TermIStream.getPrompt(): String return ((TerminalInput)args[0]).getPrompt(); case 211: // TermIStream.setPrompt(prompt: String) ((TerminalInput)args[0]).setPrompt((String)args[1]); return null; default: return null; } }
protected Object invokeNative(int index, Process p, Object[] args) throws Exception { switch (index) { /* == Header: builtin.eh == */ case 0: // acopy(src: Array, sofs: Int, dest: Array, dofs: Int, len: Int) Arrays.arrayCopy(args[0], ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 1: // Function.apply(args: [Any]): Function return new PartiallyAppliedFunction((Function)args[0], (Object[])args[1]); case 2: // throw(code: Int = FAIL, msg: String = null) throw new AlchemyException(ival(args[0]), (String)args[1]); /* == Header: string.eh == */ case 3: // Any.tostr(): String return Strings.toString(args[0]); case 4: // Char.tostr(): String return String.valueOf((char)ival(args[0])); case 5: // Int.tobin():String return Integer.toBinaryString(ival(args[0])); case 6: // Int.tooct():String return Integer.toOctalString(ival(args[0])); case 7: // Int.tohex():String return Integer.toHexString(ival(args[0])); case 8: // Int.tobase(base: Int): String return Integer.toString(ival(args[0]), ival(args[1])); case 9: // Long.tobase(base: Int): String return Long.toString(lval(args[0]), ival(args[1])); case 10: // String.tointbase(base: Int): Int return Ival(Integer.parseInt((String)args[0], ival(args[1]))); case 11: // String.tolongbase(base: Int): Long return Lval(Long.parseLong((String)args[0], ival(args[1]))); case 12: // String.tofloat(): Float return Fval(Float.parseFloat((String)args[0])); case 13: // String.todouble(): Double return Dval(Double.parseDouble((String)args[0])); case 14: { // String.get(at: Int): Char String str = (String)args[0]; int at = ival(args[1]); if (at < 0) at += str.length(); return Ival(str.charAt(at)); } case 15: // String.len(): Int return Ival(((String)args[0]).length()); case 16: { // String.range(from: Int, to: Int): String String str = (String) args[0]; int from = ival(args[1]); int to = ival(args[2]); if (from < 0) from += str.length(); if (to < 0) to += str.length(); return str.substring(from, to); } case 17: { // String.indexof(ch: Char, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf(ival(args[1]), from)); } case 18: // String.lindexof(ch: Char): Int return Ival(((String)args[0]).lastIndexOf(ival(args[1]))); case 19: { // String.find(sub: String, from: Int = 0): Int String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.indexOf((String)args[1], from)); } case 20: // String.ucase(): String return ((String)args[0]).toUpperCase(); case 21: // String.lcase(): String return ((String)args[0]).toLowerCase(); case 22: // String.concat(str: String): String return ((String)args[0]).concat((String)args[1]); case 23: // String.cmp(str: String): Int return Ival(((String)args[0]).compareTo((String)args[1])); case 24: // String.trim(): String return ((String)args[0]).trim(); case 25: // String.split(ch: Char, skipEmpty: Bool = false): [String] return Strings.split((String)args[0], (char)ival(args[1]), bval(args[2])); case 26: // String.format(args: [Any]): String return Strings.format((String)args[0], (Object[])args[1]); case 27: // String.chars(): [Char] return ((String)args[0]).toCharArray(); case 28: // String.utfbytes(): [Byte] return Strings.utfEncode((String)args[0]); case 29: { // String.startswith(prefix: String, from: Int = 0): Bool String str = (String)args[0]; int from = ival(args[2]); if (from < 0) from += str.length(); return Ival(str.startsWith((String)args[1], from)); } case 30: // String.replace(oldch: Char, newch: Char): String return ((String)args[0]).replace((char)ival(args[1]), (char)ival(args[2])); case 31: // String.hash(): Int return Ival(((String)args[0]).hashCode()); case 32: // ca2str(ca: [Char]): String return new String((char[])args[0]); case 33: // ba2utf(ba: [Byte]): String return Strings.utfDecode((byte[])args[0]); /* == Header: error.eh == */ case 34: // Error.code(): Int return Ival(((AlchemyException)args[0]).errcode); case 35: // Error.msg(): String return ((AlchemyException)args[0]).getMessage(); case 36: // Error.traceLen(): Int return Ival(((AlchemyException)args[0]).getTraceLength()); case 37: // Error.traceName(index: Int): String return ((AlchemyException)args[0]).getTraceElementName(ival(args[1])); case 38: // Error.traceDbg(index: Int): String return ((AlchemyException)args[0]).getTraceElementInfo(ival(args[1])); /* == Header: math.eh == */ case 39: // abs(val: Double): Double return Dval(Math.abs(dval(args[0]))); case 40: // sin(val: Double): Double return Dval(Math.sin(dval(args[0]))); case 41: // cos(val: Double): Double return Dval(Math.cos(dval(args[0]))); case 42: // tan(val: Double): Double return Dval(Math.tan(dval(args[0]))); case 43: // sqrt(val: Double): Double return Dval(Math.sqrt(dval(args[0]))); case 44: // ipow(val: Double, pow: Int): Double return Dval(alchemy.util.Math.ipow(dval(args[0]), ival(args[1]))); case 45: // exp(val: Double): Double return Dval(alchemy.util.Math.exp(dval(args[0]))); case 46: // log(val: Double): Double return Dval(alchemy.util.Math.log(dval(args[0]))); case 47: // asin(val: Double): Double return Dval(alchemy.util.Math.asin(dval(args[0]))); case 48: // acos(val: Double): Double return Dval(alchemy.util.Math.acos(dval(args[0]))); case 49: // atan(val: Double): Double return Dval(alchemy.util.Math.atan(dval(args[0]))); case 50: // ibits2f(bits: Int): Float return Fval(Float.intBitsToFloat(ival(args[0]))); case 51: // f2ibits(f: Float): Int return Ival(Float.floatToIntBits(fval(args[0]))); case 52: // lbits2d(bits: Long): Double return Dval(Double.longBitsToDouble(lval(args[0]))); case 53: // d2lbits(d: Double): Long return Lval(Double.doubleToLongBits(dval(args[0]))); /* == Header: rnd.eh == */ case 54: // Random.new(seed: Long) return new Random(lval(args[0])); case 55: // Random.next(n: Int): Int return Ival(((Random)args[0]).nextInt(ival(args[1]))); case 56: // Random.nextInt(): Int return Ival(((Random)args[0]).nextInt()); case 57: // Random.nextLong(): Long return Lval(((Random)args[0]).nextLong()); case 58: // Random.nextFloat(): Float return Fval(((Random)args[0]).nextFloat()); case 59: // Random.nextDouble(): Double return Dval(((Random)args[0]).nextDouble()); case 60: // Random.setSeed(seed: Long) ((Random)args[0]).setSeed(lval(args[1])); return null; /* == Header: io.eh == */ case 61: { // Connection.close() Connection conn = (Connection) args[0]; conn.close(); p.removeConnection(conn); return null; } case 62: { // StreamConnection.openInput(): IStream ConnectionInputStream in = new ConnectionInputStream(((StreamConnection)args[0]).openInputStream()); p.addConnection(in); return in; } case 63: { // StreamConnection.openOutput(): OStream ConnectionOutputStream out = new ConnectionOutputStream(((StreamConnection)args[0]).openOutputStream()); p.addConnection(out); return out; } case 64: // IStream.read(): Int return Ival(((InputStream)args[0]).read()); case 65: { // IStream.readArray(buf: [Byte], ofs: Int = 0, len: Int = -1): Int byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; return Ival(((InputStream)args[0]).read(buf, ival(args[2]), len)); } case 66: // IStream.readFully(): [Byte] return IO.readFully((InputStream)args[0]); case 67: // IStream.skip(num: Long): Long return Lval(((InputStream)args[0]).skip(lval(args[1]))); case 68: // IStream.available(): Int return Ival(((InputStream)args[0]).available()); case 69: // IStream.reset() ((InputStream)args[0]).reset(); return null; case 70: // OStream.write(b: Int) ((OutputStream)args[0]).write(ival(args[1])); return null; case 71: { // OStream.writeArray(buf: [Byte], ofs: Int, len: Int) byte[] buf = (byte[])args[1]; int len = ival(args[3]); if (len < 0) len = buf.length; ((OutputStream)args[0]).write(buf, ival(args[2]), len); return null; } case 72: // OStream.print(a: Any) IO.print((OutputStream)args[0], args[1]); return null; case 73: // OStream.println(a: Any) IO.println((OutputStream)args[0], args[1]); return null; case 74: // OStream.flush() ((OutputStream)args[0]).flush(); return null; case 75: // OStream.writeAll(input: IStream) IO.writeAll((InputStream)args[1], (OutputStream)args[0]); return null; case 76: // stdin(): IStream return p.stdin; case 77: // stdout(): OStream return p.stdout; case 78: // stderr(): OStream return p.stderr; case 79: // setin(in: IStream) p.stdin = ((InputStream)args[0]); return null; case 80: // setout(out: OStream) p.stdout = ((OutputStream)args[0]); return null; case 81: // seterr(err: OStream) p.stderr = ((OutputStream)args[0]); return null; case 82: // pathfile(path: String): String return Filesystem.fileName((String)args[0]); case 83: // pathdir(path: String): String return Filesystem.fileParent((String)args[0]); case 84: // abspath(path: String): String return p.toFile((String)args[0]); case 85: // relpath(path: String): String return Filesystem.relativePath(p.getCurrentDirectory(), p.toFile((String)args[0])); case 86: // fcreate(path: String) Filesystem.create(p.toFile((String)args[0])); return null; case 87: // fremove(path: String) Filesystem.remove(p.toFile((String)args[0])); return null; case 88: // fremoveTree(path: String) Filesystem.removeTree(p.toFile((String)args[0])); return null; case 89: // mkdir(path: String) Filesystem.mkdir(p.toFile((String)args[0])); return null; case 90: // mkdirTree(path: String) Filesystem.mkdirTree(p.toFile((String)args[0])); return null; case 91: // fcopy(source: String, dest: String) Filesystem.copy(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 92: // fmove(source: String, dest: String) Filesystem.move(p.toFile((String)args[0]), p.toFile((String)args[1])); return null; case 93: // exists(path: String): Bool return Ival(Filesystem.exists(p.toFile((String)args[0]))); case 94: // isDir(path: String): Bool return Ival(Filesystem.isDirectory(p.toFile((String)args[0]))); case 95: { // fread(path: String): IStream ConnectionInputStream input = new ConnectionInputStream(Filesystem.read(p.toFile((String)args[0]))); p.addConnection(input); return input; } case 96: { // fwrite(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.write(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 97: { // fappend(path: String): OStream ConnectionOutputStream output = new ConnectionOutputStream(Filesystem.append(p.toFile((String)args[0]))); p.addConnection(output); return output; } case 98: // flist(path: String): [String] return Filesystem.list(p.toFile((String)args[0])); case 99: // fmodified(path: String): Long return Lval(Filesystem.lastModified(p.toFile((String)args[0]))); case 100: // fsize(path: String): Long return Lval(Filesystem.size(p.toFile((String)args[0]))); case 101: // setRead(path: String, on: Bool) Filesystem.setRead(p.toFile((String)args[0]), bval(args[1])); return null; case 102: // setWrite(path: String, on: Bool) Filesystem.setWrite(p.toFile((String)args[0]), bval(args[1])); return null; case 103: // setExec(path: String, on: Bool) Filesystem.setExec(p.toFile((String)args[0]), bval(args[1])); return null; case 104: // canRead(path: String): Bool return Ival(Filesystem.canRead(p.toFile((String)args[0]))); case 105: // canWrite(path: String): Bool return Ival(Filesystem.canWrite(p.toFile((String)args[0]))); case 106: // canExec(path: String): Bool return Ival(Filesystem.canExec(p.toFile((String)args[0]))); case 107: // getCwd(): String return p.getCurrentDirectory(); case 108: // setCwd(dir: String) p.setCurrentDirectory(p.toFile((String)args[0])); return null; case 109: // spaceTotal(root: String): Long return Lval(Filesystem.spaceTotal(p.toFile((String)args[0]))); case 110: // spaceFree(root: String): Long return Lval(Filesystem.spaceFree(p.toFile((String)args[0]))); case 111: // spaceUsed(root: String): Long return Lval(Filesystem.spaceUsed(p.toFile((String)args[0]))); case 112: { // readUrl(url: String): IStream return IO.readUrl((String)args[0]); } case 113: // matchesGlob(path: String, glob: String): Bool return Ival(IO.matchesPattern((String)args[0], (String)args[1])); /* == Header: bufferio.eh == */ case 114: // BufferIStream.new(buf: [Byte]) return new ConnectionInputStream(new ByteArrayInputStream((byte[])args[0])); case 115: // BufferOStream.new() return new ConnectionOutputStream(new ByteArrayOutputStream()); case 116: // BufferOStream.len(): Int return Ival(((ByteArrayOutputStream)args[0]).size()); case 117: // BufferOStream.getBytes(): [Byte] return ((ByteArrayOutputStream)args[0]).toByteArray(); case 118: // BufferOStream.reset() ((ByteArrayOutputStream)args[0]).reset(); return null; /* == Header: pipe.eh == */ case 119: { // Pipe.new() Pipe pipe = new Pipe(); p.addConnection(pipe); return pipe; } /* == Header: strbuf.eh == */ case 120: // StrBuf.new(): StrBuf return new StringBuffer(); case 121: // StrBuf.get(at: Int): Char return Ival(((StringBuffer)args[0]).charAt(ival(args[1]))); case 122: // StrBuf.chars(from: Int, to: Int, buf: [Char], ofs: Int) ((StringBuffer)args[0]).getChars(ival(args[1]), ival(args[2]), (char[])args[3], ival(args[4])); return null; case 123: // StrBuf.append(a: Any): StrBuf return ((StringBuffer)args[0]).append(Strings.toString(args[1])); case 124: // StrBuf.addch(ch: Char): StrBuf return ((StringBuffer)args[0]).append((char)ival(args[1])); case 125: // StrBuf.insert(at: Int, a: Any): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), Strings.toString(args[2])); case 126: // StrBuf.insch(at: Int, ch: Char): StrBuf return ((StringBuffer)args[0]).insert(ival(args[1]), (char)ival(args[2])); case 127: // StrBuf.setch(at: Int, ch: Char): StrBuf ((StringBuffer)args[0]).setCharAt(ival(args[1]), (char)ival(args[2])); return args[0]; case 128: // StrBuf.delete(from: Int, to: Int): StrBuf return ((StringBuffer)args[0]).delete(ival(args[1]), ival(args[2])); case 129: // StrBuf.delch(at: Int): StrBuf return ((StringBuffer)args[0]).deleteCharAt(ival(args[1])); case 130: // StrBuf.len(): Int return Ival(((StringBuffer)args[0]).length()); /* == Header: dl.eh == */ case 131: // loadlibrary(libname: String): Library return p.loadLibrary((String)args[0]); case 132: { // buildlibrary(in: IStream): Library InputStream in = (InputStream)args[0]; if (((in.read() << 8) | in.read()) != 0xC0DE) throw new InstantiationException("Not an Ether object"); return EtherLoader.load(p, in); } case 133: // Library.getFunction(sig: String): Function return ((Library)args[0]).getFunction((String)args[1]); /* == Header: time.eh == */ case 134: // datestr(time: Long): String return new Date(lval(args[0])).toString(); case 135: { // year(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.YEAR)); } case 136: { // month(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MONTH)); } case 137: { // day(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_MONTH)); } case 138: { // dow(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.DAY_OF_WEEK)); } case 139: { // hour(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.HOUR_OF_DAY)); } case 140: { // minute(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MINUTE)); } case 141: { // second(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.SECOND)); } case 142: { // millis(time: Long): Int Calendar cal = Calendar.getInstance(); cal.setTime(new Date(lval(args[0]))); return Ival(cal.get(Calendar.MILLISECOND)); } case 143: { // timeof(year: Int, month: Int, day: Int, hour: Int, min: Int, sec: Int, millis: Int): Long Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, ival(args[0])); cal.set(Calendar.MONTH, ival(args[1])); cal.set(Calendar.DAY_OF_MONTH, ival(args[2])); cal.set(Calendar.HOUR_OF_DAY, ival(args[3])); cal.set(Calendar.MINUTE, ival(args[4])); cal.set(Calendar.SECOND, ival(args[5])); cal.set(Calendar.MILLISECOND, ival(args[6])); return Lval(cal.getTime().getTime()); } /* == Header: dict.eh == */ case 144: // Dict.new(): Dict return new HashMap(); case 145: // Dict.len(): Int return Ival(((HashMap)args[0]).size()); case 146: // Dict.get(key: Any): Any return ((HashMap)args[0]).get(args[1]); case 147: // Dict.set(key: Any, value: Any) ((HashMap)args[0]).set(args[1], args[2]); return null; case 148: // Dict.remove(key: Any) ((HashMap)args[0]).remove(args[1]); return null; case 149: // Dict.clear() ((HashMap)args[0]).clear(); return null; case 150: // Dict.keys(): [Any] return ((HashMap)args[0]).keys(); /* == Header: list.eh == */ case 151: { // List.new(a: Array = null): List ArrayList list = new ArrayList(); if (args[0] != null) list.addFrom(args[0], 0, -1); return list; } case 152: // List.len(): Int return Ival(((ArrayList)args[0]).size()); case 153: // List.get(at: Int): Any return ((ArrayList)args[0]).get(ival(args[1])); case 154: // List.set(at: Int, val: Any) ((ArrayList)args[0]).set(ival(args[1]), args[2]); return null; case 155: // List.add(val: Any) ((ArrayList)args[0]).add(args[1]); return null; case 156: // List.addFrom(arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).addFrom(args[1], ival(args[2]), ival(args[3])); return null; case 157: // List.insert(at: Int, val: Any) ((ArrayList)args[0]).insert(ival(args[1]), args[2]); return null; case 158: // List.insertfrom(at: Int, arr: Array, ofs: Int = 0, len: Int = -1) ((ArrayList)args[0]).insertFrom(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; case 159: // List.remove(at: Int) ((ArrayList)args[0]).remove(ival(args[1])); return null; case 160: // List.clear() ((ArrayList)args[0]).clear(); return null; case 161: // List.range(from: Int, to: Int): List return ((ArrayList)args[0]).getRange(ival(args[1]), ival(args[2])); case 162: // List.indexof(val: Any, from: Int = 0): Int return Ival(((ArrayList)args[0]).indexOf(args[1], ival(args[2]))); case 163: // List.lindexof(val: Any): Int return Ival(((ArrayList)args[0]).lastIndexOf(args[1])); case 164: { // List.filter(f: (Any):Bool): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { Object e = oldlist.get(i); if (f.invoke(p, new Object[] {oldlist.get(i)}) == Int32.ONE) { newlist.add(e); } } return newlist; } case 165: { // List.filterself(f: (Any):Bool) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); int i=0; while (i < len) { if (f.invoke(p, new Object[] {list.get(i)}) == Int32.ONE) { i++; } else { list.remove(i); len--; } } return null; } case 166: { // List.map(f: (Any):Any): List ArrayList oldlist = (ArrayList)args[0]; int len = oldlist.size(); ArrayList newlist = new ArrayList(len); Function f = (Function)args[1]; for (int i=0; i<len; i++) { newlist.add(f.invoke(p, new Object[] {oldlist.get(i)})); } return newlist; } case 167: { // List.mapself(f: (Any):Any) ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); for (int i=0; i<len; i++) { list.set(i, f.invoke(p, new Object[] {list.get(i)})); } return null; } case 168: { // List.reduce(f: (Any,Any):Any): Any ArrayList list = (ArrayList)args[0]; Function f = (Function)args[1]; int len = list.size(); if (len == 0) return null; Object ret = list.get(0); Object[] fparams = new Object[2]; for (int i=1; i<len; i++) { fparams[0] = ret; fparams[1] = list.get(i); ret = f.invoke(p, fparams); } return ret; } case 169: { // List.sort(f: (Any,Any):Int): List ArrayList oldList = (ArrayList)args[0]; Object[] data = new Object[oldList.size()]; oldList.copyInto(data); if (data.length > 0) { Arrays.qsort(data, 0, data.length-1, p, (Function)args[1]); } ArrayList newList = new ArrayList(data.length); newList.addFrom(data, 0, data.length); return newList; } case 170: { // List.sortself(f: (Any,Any):Int) ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); if (data.length > 0) { Arrays.qsort(data, 0, data.length-1, p, (Function)args[1]); } list.clear(); list.addFrom(data, 0, data.length); return null; } case 171: { // List.reverse(): List ArrayList oldList = (ArrayList)args[0]; int len = oldList.size(); ArrayList newList = new ArrayList(len); for (int i=len-1; i>=0; i--) { newList.add(oldList.get(i)); } return newList; } case 172: { // List.toarray(): [Any] ArrayList list = (ArrayList)args[0]; Object[] data = new Object[list.size()]; list.copyInto(data); return data; } case 173: // List.copyInto(from: Int, buf: Array, ofs: Int, len: Int) ((ArrayList)args[0]).copyInto(ival(args[1]), args[2], ival(args[3]), ival(args[4])); return null; /* == Header: thread.eh == */ case 174: // currentThread(): Thread return Thread.currentThread(); case 175: // Thread.new(run: ()); return p.createThread((Function)args[0]); case 176: // Thread.start() ((ProcessThread)args[0]).start(); return null; case 177: // Thread.isAlive(): Bool return Ival(((ProcessThread)args[0]).isAlive()); case 178: // Thread.interrupt() ((ProcessThread)args[0]).interrupt(); return null; case 179: // Thread.isInterrupted(): Bool return Ival(((ProcessThread)args[0]).isInterrupted()); case 180: // Thread.join() ((ProcessThread)args[0]).join(); return null; case 181: // Lock.new() return new Lock(); case 182: // Lock.lock() ((Lock)args[0]).lock(); return null; case 183: // Lock.tryLock(): Bool return Ival(((Lock)args[0]).tryLock()); case 184: // Lock.unlock() ((Lock)args[0]).unlock(); return null; /* == Header: process.eh == */ case 185: // currentProcess(): Process return p; case 186: { // Process.new(cmd: String, args: [String]) Object[] objArgs = (Object[])args[1]; String[] strArgs = new String[objArgs.length]; System.arraycopy(objArgs, 0, strArgs, 0, objArgs.length); return new Process(p, (String)args[0], strArgs); } case 187: // Process.getState(): Int return Ival(((Process)args[0]).getState()); case 188: // Process.getPriority(): Int return Ival(((Process)args[0]).getPriority()); case 189: { // Process.setPriority(value: Int) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setPriority(ival(args[1])); return null; } else { throw new SecurityException(); } } case 190: // Process.getName(): String return ((Process)args[0]).getName(); case 191: // Process.getArgs(): [String] return ((Process)args[0]).getArgs(); case 192: { // Process.setEnv(key: String, value: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setEnv((String)args[1], (String)args[2]); return null; } else { throw new SecurityException(); } } case 193: { // Process.setIn(in: IStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdin = (InputStream)args[1]; return null; } else { throw new SecurityException(); } } case 194: { // Process.setOut(out: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stdout = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 195: { // Process.setErr(err: OStream) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.stderr = (OutputStream)args[1]; return null; } else { throw new SecurityException(); } } case 196: { // Process.setCwd(cwd: String) Process process = (Process)args[0]; if (process == p || process.getState() == Process.NEW) { process.setCurrentDirectory(p.toFile((String)args[1])); return null; } else { throw new SecurityException(); } } case 197: // Process.start(): Process return ((Process)args[0]).start(); case 198: // Process.waitFor(): Int return Ival(((Process)args[0]).waitFor()); case 199: // Process.kill() ((Process)args[0]).kill(); return null; case 200: // Process.getExitCode(): Int return Ival(((Process)args[0]).getExitCode()); case 201: // Process.getError(): Error return ((Process)args[0]).getError(); /* == Header: sys.eh == */ case 202: // systime(): Long return Lval(System.currentTimeMillis()); case 203: // getenv(key: String): String return p.getEnv((String)args[0]); case 204: // setenv(key: String, val: String) p.setEnv((String)args[0], (String)args[1]); return null; case 205: // sleep(millis: Int) Thread.sleep(lval(args[0])); return null; case 206: // sysProperty(str: String): String return System.getProperty((String)args[0]); case 207: // platformRequest(url: String): Bool return Ival(Platform.getPlatform().getCore().platformRequest((String)args[0])); /* == Header: term.eh == */ case 208: // isTerm(stream: IStream): Bool return Ival(args[0] instanceof TerminalInput); case 209: // TermIStream.clear() ((TerminalInput)args[0]).clear(); return null; case 210: // TermIStream.getPrompt(): String return ((TerminalInput)args[0]).getPrompt(); case 211: // TermIStream.setPrompt(prompt: String) ((TerminalInput)args[0]).setPrompt((String)args[1]); return null; default: return null; } }
diff --git a/CardTactics/src/com/kongentertainment/android/cardtactics/view/CreatureYardView.java b/CardTactics/src/com/kongentertainment/android/cardtactics/view/CreatureYardView.java index 548db8f..3518c67 100644 --- a/CardTactics/src/com/kongentertainment/android/cardtactics/view/CreatureYardView.java +++ b/CardTactics/src/com/kongentertainment/android/cardtactics/view/CreatureYardView.java @@ -1,66 +1,66 @@ package com.kongentertainment.android.cardtactics.view; import android.graphics.Bitmap; import android.graphics.Canvas; import com.kongentertainment.android.cardtactics.model.entities.CreatureCard; import com.kongentertainment.android.cardtactics.model.entities.CreatureYard; import com.kongentertainment.android.cardtactics.model.exceptions.InvalidMoveException; public class CreatureYardView { //PERF: Chop these down to shorts/chars if need be private static int YARD_X_POS = 150; private static int YARD_Y_POS = 195; //private static int YARD_X_SIZE = 200; //private static int YARD_Y_SIZE = 160; private static int CELL_WIDTH = 66; private static int CELL_HEIGHT = 53; /** The Creature Yard to pull data from */ private CreatureYard mCreatureYard; private CardViewManager mCardViewManager; /** DEBUG ONLY */ public CreatureYardView(String debug) { int yard_x = 3; int yard_y = 2; mCreatureYard = new CreatureYard(yard_x, yard_y); CreatureCard creature = new CreatureCard("Debug"); for (int x=0; x<yard_x; x++) { for (int y=0; y<yard_y; y++) { try { mCreatureYard.addCreature(creature, x, y); } catch (InvalidMoveException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public CreatureYardView(CreatureYard creatureYard) { mCreatureYard = creatureYard; } /** * The meat of the class. This fetches the relevant bitmaps and draws them * in the proper positions. */ public void draw(Canvas canvas) { int x = mCreatureYard.getWidth(); int y = mCreatureYard.getHeight(); //For each position for (int i=0; i < x; i++) { for (int j=0; j < y; j++) { //if occupied - if (!mCreatureYard.isEmpty(x, y)) { - int cardID = mCreatureYard.getCreature(x, y).getID(); + if (!mCreatureYard.isEmpty(i, j)) { + int cardID = mCreatureYard.getCreature(i, j).getID(); Bitmap bitmap = mCardViewManager.getBigCard(cardID); //draw a card there int xCoord = YARD_X_POS + CELL_WIDTH * x; int yCoord = YARD_Y_POS + CELL_HEIGHT * y; canvas.drawBitmap(bitmap, xCoord, yCoord, null); } //else keep going } } } }
true
true
public void draw(Canvas canvas) { int x = mCreatureYard.getWidth(); int y = mCreatureYard.getHeight(); //For each position for (int i=0; i < x; i++) { for (int j=0; j < y; j++) { //if occupied if (!mCreatureYard.isEmpty(x, y)) { int cardID = mCreatureYard.getCreature(x, y).getID(); Bitmap bitmap = mCardViewManager.getBigCard(cardID); //draw a card there int xCoord = YARD_X_POS + CELL_WIDTH * x; int yCoord = YARD_Y_POS + CELL_HEIGHT * y; canvas.drawBitmap(bitmap, xCoord, yCoord, null); } //else keep going } } }
public void draw(Canvas canvas) { int x = mCreatureYard.getWidth(); int y = mCreatureYard.getHeight(); //For each position for (int i=0; i < x; i++) { for (int j=0; j < y; j++) { //if occupied if (!mCreatureYard.isEmpty(i, j)) { int cardID = mCreatureYard.getCreature(i, j).getID(); Bitmap bitmap = mCardViewManager.getBigCard(cardID); //draw a card there int xCoord = YARD_X_POS + CELL_WIDTH * x; int yCoord = YARD_Y_POS + CELL_HEIGHT * y; canvas.drawBitmap(bitmap, xCoord, yCoord, null); } //else keep going } } }
diff --git a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/common/Util.java b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/common/Util.java index caa82113..271cade2 100644 --- a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/common/Util.java +++ b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/common/Util.java @@ -1,274 +1,274 @@ /******************************************************************************* * Copyright (c) 2010 BestSolution.at and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tom Schindl <[email protected]> - initial API and implementation ******************************************************************************/ package org.eclipse.e4.tools.emf.ui.common; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.observable.value.IValueChangeListener; import org.eclipse.core.databinding.observable.value.ValueChangeEvent; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IStatus; import org.eclipse.e4.tools.emf.ui.common.IEditorFeature.FeatureClass; import org.eclipse.e4.ui.model.application.MApplicationElement; import org.eclipse.e4.ui.model.application.impl.ApplicationPackageImpl; import org.eclipse.e4.ui.model.application.ui.MElementContainer; import org.eclipse.e4.ui.model.application.ui.MUIElement; import org.eclipse.e4.ui.model.application.ui.impl.UiPackageImpl; import org.eclipse.e4.ui.model.fragment.impl.FragmentPackageImpl; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.edit.command.MoveCommand; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Control; public class Util { public static final boolean isNullOrEmpty(String element) { return element == null || element.trim().length() == 0; } public static final boolean isImport(EObject object) { return object.eContainingFeature() == FragmentPackageImpl.Literals.MODEL_FRAGMENTS__IMPORTS; } public static final void addClasses(EPackage ePackage, List<FeatureClass> list) { for (EClassifier c : ePackage.getEClassifiers()) { if (c instanceof EClass) { EClass eclass = (EClass) c; if (eclass != ApplicationPackageImpl.Literals.APPLICATION && !eclass.isAbstract() && !eclass.isInterface() && eclass.getEAllSuperTypes().contains(ApplicationPackageImpl.Literals.APPLICATION_ELEMENT)) { list.add(new FeatureClass(eclass.getName(), eclass)); } } } for (EPackage eSubPackage : ePackage.getESubpackages()) { addClasses(eSubPackage, list); } } // TODO In future support different name formats something like // ${project}.${classname}.${counter} public static final String getDefaultElementId(Resource resource, MApplicationElement element, IProject project) { try { EObject o = (EObject) element; String className = o.eClass().getName(); String projectName = project.getName(); String prefix = projectName + "." + className; //$NON-NLS-1$ TreeIterator<EObject> it = resource.getAllContents(); SortedSet<Integer> numbers = new TreeSet<Integer>(); while (it.hasNext()) { EObject tmp = it.next(); if (tmp instanceof MApplicationElement) { String elementId = ((MApplicationElement) tmp).getElementId(); if (elementId != null && elementId.length() > prefix.length() && elementId.startsWith(prefix)) { String suffix = elementId.substring(prefix.length()); if (suffix.startsWith(".") && suffix.length() > 1) { //$NON-NLS-1$ try { numbers.add(Integer.parseInt(suffix.substring(1))); } catch (Exception e) { // TODO: handle exception } } } } } int lastNumber = -1; for (Integer number : numbers) { if ((lastNumber + 1) != number) { break; } lastNumber = number; } - return prefix + "." + ++lastNumber; //$NON-NLS-1$ + return (prefix + "." + ++lastNumber).toLowerCase(); //$NON-NLS-1$ } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } public static List<InternalPackage> loadPackages() { List<InternalPackage> packs = new ArrayList<InternalPackage>(); for (Entry<String, Object> regEntry : EPackage.Registry.INSTANCE.entrySet()) { if (regEntry.getValue() instanceof EPackage) { EPackage ePackage = (EPackage) regEntry.getValue(); InternalPackage iePackage = new InternalPackage(ePackage); boolean found = false; for (EClassifier cl : ePackage.getEClassifiers()) { if (cl instanceof EClass) { EClass eClass = (EClass) cl; if (eClass.getEAllSuperTypes().contains(ApplicationPackageImpl.Literals.APPLICATION_ELEMENT)) { if (!eClass.isInterface() && !eClass.isAbstract()) { found = true; InternalClass ieClass = new InternalClass(iePackage, eClass); iePackage.classes.add(ieClass); for (EReference f : eClass.getEAllReferences()) { ieClass.features.add(new InternalFeature(ieClass, f)); } } } } } if (found) { packs.add(iePackage); } } } return packs; } public static boolean moveElementByIndex(EditingDomain editingDomain, MUIElement element, boolean liveModel, int index, EStructuralFeature feature) { if (liveModel) { EObject container = ((EObject) element).eContainer(); List<Object> l = (List<Object>) container.eGet(feature); l.remove(element); if (index >= 0) { l.add(index, element); } else { l.add(element); } return true; } else { EObject container = ((EObject) element).eContainer(); Command cmd = MoveCommand.create(editingDomain, container, feature, element, index); if (cmd.canExecute()) { editingDomain.getCommandStack().execute(cmd); return true; } return false; } } public static boolean moveElementByIndex(EditingDomain editingDomain, MUIElement element, boolean liveModel, int index) { if (liveModel) { MElementContainer<MUIElement> container = element.getParent(); container.getChildren().remove(element); if (index >= 0) { container.getChildren().add(index, element); } else { container.getChildren().add(element); } container.setSelectedElement(element); return true; } else { MElementContainer<MUIElement> container = element.getParent(); Command cmd = MoveCommand.create(editingDomain, container, UiPackageImpl.Literals.ELEMENT_CONTAINER__CHILDREN, element, index); if (cmd.canExecute()) { editingDomain.getCommandStack().execute(cmd); return true; } return false; } } public static final void addDecoration(Control control, Binding binding) { final ControlDecoration dec = new ControlDecoration(control, SWT.BOTTOM); binding.getValidationStatus().addValueChangeListener(new IValueChangeListener() { public void handleValueChange(ValueChangeEvent event) { IStatus s = (IStatus) event.getObservableValue().getValue(); if (s.isOK()) { dec.setDescriptionText(null); dec.setImage(null); } else { dec.setDescriptionText(s.getMessage()); String fieldDecorationID = null; switch (s.getSeverity()) { case IStatus.INFO: fieldDecorationID = FieldDecorationRegistry.DEC_INFORMATION; break; case IStatus.WARNING: fieldDecorationID = FieldDecorationRegistry.DEC_WARNING; break; case IStatus.ERROR: case IStatus.CANCEL: fieldDecorationID = FieldDecorationRegistry.DEC_ERROR; break; } FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(fieldDecorationID); dec.setImage(fieldDecoration == null ? null : fieldDecoration.getImage()); } } }); } public static class InternalPackage { public final EPackage ePackage; public List<InternalClass> classes = new ArrayList<InternalClass>(); public InternalPackage(EPackage ePackage) { this.ePackage = ePackage; } @Override public String toString() { return ePackage.toString(); } public List<EClass> getAllClasses() { ArrayList<EClass> rv = new ArrayList<EClass>(classes.size()); for (InternalClass c : classes) { rv.add(c.eClass); } return rv; } } public static class InternalClass { public final InternalPackage pack; public final EClass eClass; public List<InternalFeature> features = new ArrayList<InternalFeature>(); public InternalClass(InternalPackage pack, EClass eClass) { this.eClass = eClass; this.pack = pack; } } public static class InternalFeature { public final InternalClass clazz; public final EStructuralFeature feature; public InternalFeature(InternalClass clazz, EStructuralFeature feature) { this.clazz = clazz; this.feature = feature; } } }
true
true
public static final String getDefaultElementId(Resource resource, MApplicationElement element, IProject project) { try { EObject o = (EObject) element; String className = o.eClass().getName(); String projectName = project.getName(); String prefix = projectName + "." + className; //$NON-NLS-1$ TreeIterator<EObject> it = resource.getAllContents(); SortedSet<Integer> numbers = new TreeSet<Integer>(); while (it.hasNext()) { EObject tmp = it.next(); if (tmp instanceof MApplicationElement) { String elementId = ((MApplicationElement) tmp).getElementId(); if (elementId != null && elementId.length() > prefix.length() && elementId.startsWith(prefix)) { String suffix = elementId.substring(prefix.length()); if (suffix.startsWith(".") && suffix.length() > 1) { //$NON-NLS-1$ try { numbers.add(Integer.parseInt(suffix.substring(1))); } catch (Exception e) { // TODO: handle exception } } } } } int lastNumber = -1; for (Integer number : numbers) { if ((lastNumber + 1) != number) { break; } lastNumber = number; } return prefix + "." + ++lastNumber; //$NON-NLS-1$ } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; }
public static final String getDefaultElementId(Resource resource, MApplicationElement element, IProject project) { try { EObject o = (EObject) element; String className = o.eClass().getName(); String projectName = project.getName(); String prefix = projectName + "." + className; //$NON-NLS-1$ TreeIterator<EObject> it = resource.getAllContents(); SortedSet<Integer> numbers = new TreeSet<Integer>(); while (it.hasNext()) { EObject tmp = it.next(); if (tmp instanceof MApplicationElement) { String elementId = ((MApplicationElement) tmp).getElementId(); if (elementId != null && elementId.length() > prefix.length() && elementId.startsWith(prefix)) { String suffix = elementId.substring(prefix.length()); if (suffix.startsWith(".") && suffix.length() > 1) { //$NON-NLS-1$ try { numbers.add(Integer.parseInt(suffix.substring(1))); } catch (Exception e) { // TODO: handle exception } } } } } int lastNumber = -1; for (Integer number : numbers) { if ((lastNumber + 1) != number) { break; } lastNumber = number; } return (prefix + "." + ++lastNumber).toLowerCase(); //$NON-NLS-1$ } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; }
diff --git a/mediators/src/main/java/org/sciflex/plugins/synapse/esper/mediators/AxiomMediator.java b/mediators/src/main/java/org/sciflex/plugins/synapse/esper/mediators/AxiomMediator.java index 78a0156..4b2efc2 100644 --- a/mediators/src/main/java/org/sciflex/plugins/synapse/esper/mediators/AxiomMediator.java +++ b/mediators/src/main/java/org/sciflex/plugins/synapse/esper/mediators/AxiomMediator.java @@ -1,555 +1,555 @@ /* * SCI-Flex: Flexible Integration of SOA and CEP * Copyright (C) 2008, 2009 http://sci-flex.org * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.sciflex.plugins.synapse.esper.mediators; import java.io.ByteArrayInputStream; import java.io.File; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import com.espertech.esper.client.Configuration; import com.espertech.esper.client.ConfigurationException; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.EventTypeException; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMSourcedElement; import org.apache.axiom.om.ds.MapDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.ManagedLifecycle; import org.apache.synapse.Mediator; import org.apache.synapse.MessageContext; import org.apache.synapse.core.SynapseEnvironment; import org.sciflex.plugins.synapse.esper.core.activities.MonitoredMediatorActivity; import org.sciflex.plugins.synapse.esper.core.workflows.MonitoredRequestResponseWorkflow; import org.sciflex.plugins.synapse.esper.core.util.UniquelyIdentifiableChild; import org.sciflex.plugins.synapse.esper.core.util.UUIDGenerator; import org.sciflex.plugins.synapse.esper.mediators.editors.CEPInstanceEditor; import org.sciflex.plugins.synapse.esper.mediators.helpers.AdminComponentStore; import org.sciflex.plugins.synapse.esper.mediators.helpers.EPLStatementHelper; import org.sciflex.plugins.synapse.esper.mediators.helpers.InvokableEPLStatementHelper; import org.sciflex.plugins.synapse.esper.mediators.monitors.MediatorActivityMonitor; import org.sciflex.plugins.synapse.esper.mediators.monitors.MediatorStatisticsMonitor; import org.w3c.dom.Document; /** * Class Mediator which can be used to connect Esper to synapse through its * Axiom communication API. This mediator is designed to be referrenced by the * synapse.xml. * <p> * A sample synapse.xml file is found in the examples folder. * @see XMLMediator */ public class AxiomMediator implements SynapseEsperMediator { /** * Log associated with the Axiom Mediator. */ private static final Log log = LogFactory.getLog(AxiomMediator.class); /** * Trace State. */ private int traceState = 0; /** * The Instance URI to be used by EPServiceProviderManager. * @see com.espertech.esper.client.EPServiceProviderManager */ private String instanceURI = null; /** * Esper Configuration instance. */ protected Configuration configuration = new Configuration(); /** * Synapse Listener Instance. */ private SynapseListener listener = null; /** * Helper to handle EPL statements. */ private InvokableEPLStatementHelper eplStatementHelper = null; /** * Indicates that the Mediator is {@link Map} aware. */ private boolean isMapAware = false; /** * Monitors mediator activities. */ private MonitoredMediatorActivity activityMonitor = null; /** * Monitors mediator statistics. */ private MonitoredRequestResponseWorkflow statMonitor = null; /** * Admin component store. */ private AdminComponentStore componentStore = null; /** * Unique Identifier of this object. */ private String uid = null; /** * The Alias of Mediator */ private String alias = null; /** * Whether inactive at start */ private boolean inactive = false; /** * Object used to control access to {@link #getProvider}. Please * note that the {@link #mediate} method is calling getProvider() * without using this lock, for achieving higher concurrency levels * and any change to the outcome of {@link #getProvider} must * involve, temporarily stopping the mediator activity. A change to * {@link #getProvider} is considered a configuration change. */ private Object providerLock = new Object(); /** * Sets the EventToAddress. Please set listener before setting the * EventToAddress. * @param uri URI of To Address associated with Event. */ public void setEventToAddress(String uri) { if (listener != null) listener.setEventToAddress(uri); else log.error("Listener has not been set"); } /** * Sets the Esper Configuration details. * @param path Path to configuration file. */ public void setConfiguration(String path) { log.debug("Setting configuration " + path); try { File file = new File(path); configuration.configure(file); log.info("Setting configuration complete"); } catch (Exception e) { log.error("An error occured while setting the configuration " + e.getMessage()); } } /** * Sets the Esper Configuration details from an Axiom Element describing * the various details. * @param config Configuration Axiom Element. */ public void setConfiguration(OMElement config) { log.debug("Setting configuration " + config); try { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse( new ByteArrayInputStream(config.toString().getBytes())); configuration.configure(doc); log.info("Setting configuration complete"); } catch (Exception e) { log.error("An error occured while setting the configuration " + e.getMessage()); } } /** * Gets the Trace State. * @return Trace State. */ public int getTraceState() { return traceState; } /** * Sets the Trace State. * @param state Trace State. */ public void setTraceState(int state) { traceState = state; } /** * Gets the Alias of Mediator * @return Alias of Mediator. */ public String getAlias() { return alias; } /** * Sets the Alias of Mediator. * @param alias Alias of Mediator. */ public void setAlias(String alias) { this.alias = alias; } /** * Sets the Instance URI. * @param uri the Instance URI. */ public synchronized void setInstanceURI(String uri) { log.debug("Setting Instance URI " + uri); if (activityMonitor != null) { log.debug("Disabling Mediator Activity"); activityMonitor.stopMediator(); } synchronized(providerLock) { instanceURI = uri; if (eplStatementHelper != null) { eplStatementHelper.changeProvider(getProvider()); } } if (activityMonitor != null) { log.debug("Enabling Mediator Activity"); activityMonitor.startMediator(); } } /** * Gets the Instance URI. * @return the Instance URI. */ public String getInstanceURI() { return instanceURI; } /** * Sets whether the Mediator is {@link Map} aware. * @param status this should be "true" if the Mediator * is to be Map aware. */ public void setIsMapAware(String status) { isMapAware = Boolean.valueOf(status); if (isMapAware) { log.info("Mediator is Map aware"); } else { log.info("Mediator is not Map aware"); } } /** * Sets associated listener. * @param name name of listener class. */ public void setListener(String name) { log.debug("Setting listener " + name); try { Class listenerClass = Class.forName(name); if (listenerClass == null) { log.error("Invalid Class Name"); return; } Object o = listenerClass.newInstance(); if (o instanceof SynapseListener) { listener = (SynapseListener) o; log.info("Listener " + name + " was successfully setup"); } else log.error("Setting listener failed"); } catch (ClassNotFoundException e) { log.error("Class " + name + " was not found"); } catch (Exception e) { log.error("Setting listener failed " + e.getMessage()); } } /** * Sets the EPL Statement. This method is called only at init. * Subsequent invocations must be precedeed and followed by * disabling and enabling the mediator activity. * @param epl the EPL Statement element. */ public void setStatement(OMElement epl) { if (listener == null) { listener = new SynapseListenerImpl(); } log.debug("Setting EPL statement " + epl); String value = epl.getAttributeValue(new QName("value")); if (value == null) { value = epl.getAttributeValue(new QName("key")); if (value == null) { log.error("Setting EPL statement failed. Got " + epl); return; } else { log.debug("Setting EPL statment using registry key " + value); synchronized(providerLock) { eplStatementHelper = new EPLStatementHelper( EPLStatementHelper.EPLStatementType.INDIRECT, value, getProvider(), listener); } if (componentStore != null) { componentStore.changeEPLStatementHelper((EPLStatementHelper)eplStatementHelper); } } } else { log.debug("Setting EPL statement " + value); synchronized(providerLock) { eplStatementHelper = new EPLStatementHelper(value, getProvider(), listener); } if (componentStore != null) { componentStore.changeEPLStatementHelper((EPLStatementHelper)eplStatementHelper); } } } /** * Sets the EPL Statement. This method is called only at init. * Subsequent invocations must be precedeed and followed by * disabling and enabling the mediator activity. * @param epl the EPL Statement. */ public void setStatement(String epl) { if (listener == null) { listener = new SynapseListenerImpl(); } log.debug("Setting EPL statement " + epl); synchronized(providerLock) { eplStatementHelper = new EPLStatementHelper(epl, getProvider(), listener); } if (componentStore != null) { componentStore.changeEPLStatementHelper((EPLStatementHelper)eplStatementHelper); } } /** * Sets the mediator as inactive at the beginning. * @param state whether inactive or not. */ public void setInactive(boolean state) { inactive = state; } /** * Gets an EPServiceProvider based on Mediator configuration details. * @return EPServiceProvider instance. */ private EPServiceProvider getProvider() { try { if (instanceURI == null && configuration == null) return EPServiceProviderManager.getDefaultProvider(); else if (instanceURI == null) return EPServiceProviderManager .getDefaultProvider(configuration); else if (configuration == null) return EPServiceProviderManager.getProvider(instanceURI); else return EPServiceProviderManager.getProvider(instanceURI, configuration); } catch (ConfigurationException e) { log.error("An error occured while retrieving provider " + e.getMessage()); return null; } } /** * Invokes the mediator passing the current message for mediation. * @param mc Message Context of the current message. * @return returns true if mediation should continue, or false if further * mediation should be aborted. */ public boolean mediate(MessageContext mc) { if (activityMonitor != null && !activityMonitor.getIsMediatorActive()) { log.warn("Cannot mediate. Mediator is inactive"); - return true; + return false; } long activityStamp = System.currentTimeMillis(); log.trace("Beginning Mediation"); // There is no providerLock in place at this point, to enable maximum // concurrent use of the mediate method. However, if someone is to // acquire a providerLock, that person must ensure that the mediate // method is not called. EPServiceProvider provider = getProvider(); if (provider == null) { /* * There should be an error if we couldn't obtain the provider. * Therefore, stop mediation */ return false; } if (componentStore != null) { componentStore.invoke(mc); } eplStatementHelper.invoke(mc); // It takes this long to make the request. // You will have to setup all the required resources // to proceed with the servicing of the request. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleRequest(ts - activityStamp); activityStamp = ts; } OMElement bodyElement = null; try { bodyElement = mc.getEnvelope().getBody().getFirstElement(); } catch (OMException e) { log.warn("An error occured while reading message " + e.getMessage()); // We don't mind an error while reading a message. return true; } if (bodyElement == null) { // FIXME Figure out proper response for null element. return true; } boolean handleMap = isMapAware; if (handleMap) { if (!(bodyElement instanceof OMSourcedElement) || !( ((OMSourcedElement)bodyElement).getDataSource() != null && ((OMSourcedElement)bodyElement).getDataSource() instanceof MapDataSource)) { handleMap = false; } } if (!handleMap) { bodyElement.build(); try { provider.getEPRuntime().getEventSender("AxiomEvent") .sendEvent(bodyElement); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } else { try { log.trace("Generating " + Map.class.getName() + " Event"); OMSourcedElement omse = (OMSourcedElement)bodyElement; MapDataSource mds = (MapDataSource)omse.getDataSource(); Map bodyMap = (Map)mds.getObject(); if (bodyMap == null) { // FIXME Figure out proper response for null element. return true; } provider.getEPRuntime().sendEvent(bodyMap, "AxiomEvent"); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } // You have to get here to say the mediator responded. // All other returns are failures rather. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleResponse(ts - activityStamp); } return true; } /** * Destruction of Initialized resources. */ public void destroy() { if (activityMonitor != null) { log.debug("Disabling Mediator Activity"); activityMonitor.stopMediator(); activityMonitor = null; } if (statMonitor != null) { log.debug("Disabling Statistics Monitoring"); statMonitor = null; } if (componentStore != null) { log.debug("Destroying Component Store"); componentStore.destroy(); } } /** * Initialization of resources. * @param se Synapse Environment passed by configuration. */ public void init(SynapseEnvironment se) { // hack to get round lack of init(SynapseEnv) on mediator interface. if (listener != null) { listener.setSynapseEnvironment(se); if (statMonitor == null) { log.debug("Enabling Statistics Monitoring"); statMonitor = new MediatorStatisticsMonitor(this); } if (activityMonitor == null) { log.debug("Enabling Mediator Activity"); activityMonitor = new MediatorActivityMonitor(this); if (!inactive) { activityMonitor.startMediator(); } else { activityMonitor.startMediator(); activityMonitor.stopMediator(); } } componentStore = new AdminComponentStore(this); componentStore.addUniquelyIdentifiableChild((UniquelyIdentifiableChild)statMonitor); componentStore.addUniquelyIdentifiableChild(activityMonitor); componentStore.addUniquelyIdentifiableChild(new CEPInstanceEditor(this)); if (eplStatementHelper != null && eplStatementHelper instanceof EPLStatementHelper) { componentStore.changeEPLStatementHelper((EPLStatementHelper)eplStatementHelper); } } else { log.error("Listener has not been set"); } } /** * Returns the Unique Identifier of the resource. * * @return the Unique Identifier of the resource. */ public String getUID() { if (uid == null) { uid = UUIDGenerator.createUUID(); } return uid; } /** * Returns the Type of the resource. * * @return the Type of the resource. */ public String getType() { return AxiomMediator.class.getName(); } }
true
true
public boolean mediate(MessageContext mc) { if (activityMonitor != null && !activityMonitor.getIsMediatorActive()) { log.warn("Cannot mediate. Mediator is inactive"); return true; } long activityStamp = System.currentTimeMillis(); log.trace("Beginning Mediation"); // There is no providerLock in place at this point, to enable maximum // concurrent use of the mediate method. However, if someone is to // acquire a providerLock, that person must ensure that the mediate // method is not called. EPServiceProvider provider = getProvider(); if (provider == null) { /* * There should be an error if we couldn't obtain the provider. * Therefore, stop mediation */ return false; } if (componentStore != null) { componentStore.invoke(mc); } eplStatementHelper.invoke(mc); // It takes this long to make the request. // You will have to setup all the required resources // to proceed with the servicing of the request. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleRequest(ts - activityStamp); activityStamp = ts; } OMElement bodyElement = null; try { bodyElement = mc.getEnvelope().getBody().getFirstElement(); } catch (OMException e) { log.warn("An error occured while reading message " + e.getMessage()); // We don't mind an error while reading a message. return true; } if (bodyElement == null) { // FIXME Figure out proper response for null element. return true; } boolean handleMap = isMapAware; if (handleMap) { if (!(bodyElement instanceof OMSourcedElement) || !( ((OMSourcedElement)bodyElement).getDataSource() != null && ((OMSourcedElement)bodyElement).getDataSource() instanceof MapDataSource)) { handleMap = false; } } if (!handleMap) { bodyElement.build(); try { provider.getEPRuntime().getEventSender("AxiomEvent") .sendEvent(bodyElement); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } else { try { log.trace("Generating " + Map.class.getName() + " Event"); OMSourcedElement omse = (OMSourcedElement)bodyElement; MapDataSource mds = (MapDataSource)omse.getDataSource(); Map bodyMap = (Map)mds.getObject(); if (bodyMap == null) { // FIXME Figure out proper response for null element. return true; } provider.getEPRuntime().sendEvent(bodyMap, "AxiomEvent"); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } // You have to get here to say the mediator responded. // All other returns are failures rather. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleResponse(ts - activityStamp); } return true; }
public boolean mediate(MessageContext mc) { if (activityMonitor != null && !activityMonitor.getIsMediatorActive()) { log.warn("Cannot mediate. Mediator is inactive"); return false; } long activityStamp = System.currentTimeMillis(); log.trace("Beginning Mediation"); // There is no providerLock in place at this point, to enable maximum // concurrent use of the mediate method. However, if someone is to // acquire a providerLock, that person must ensure that the mediate // method is not called. EPServiceProvider provider = getProvider(); if (provider == null) { /* * There should be an error if we couldn't obtain the provider. * Therefore, stop mediation */ return false; } if (componentStore != null) { componentStore.invoke(mc); } eplStatementHelper.invoke(mc); // It takes this long to make the request. // You will have to setup all the required resources // to proceed with the servicing of the request. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleRequest(ts - activityStamp); activityStamp = ts; } OMElement bodyElement = null; try { bodyElement = mc.getEnvelope().getBody().getFirstElement(); } catch (OMException e) { log.warn("An error occured while reading message " + e.getMessage()); // We don't mind an error while reading a message. return true; } if (bodyElement == null) { // FIXME Figure out proper response for null element. return true; } boolean handleMap = isMapAware; if (handleMap) { if (!(bodyElement instanceof OMSourcedElement) || !( ((OMSourcedElement)bodyElement).getDataSource() != null && ((OMSourcedElement)bodyElement).getDataSource() instanceof MapDataSource)) { handleMap = false; } } if (!handleMap) { bodyElement.build(); try { provider.getEPRuntime().getEventSender("AxiomEvent") .sendEvent(bodyElement); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } else { try { log.trace("Generating " + Map.class.getName() + " Event"); OMSourcedElement omse = (OMSourcedElement)bodyElement; MapDataSource mds = (MapDataSource)omse.getDataSource(); Map bodyMap = (Map)mds.getObject(); if (bodyMap == null) { // FIXME Figure out proper response for null element. return true; } provider.getEPRuntime().sendEvent(bodyMap, "AxiomEvent"); log.trace("Ending Mediation"); } catch (EventTypeException e) { log.error("Invalid Event Type " + e.getMessage()); } catch (Exception e) { log.error("An error occured while sending Event " + e.getMessage()); } } // You have to get here to say the mediator responded. // All other returns are failures rather. if (statMonitor != null) { long ts = System.currentTimeMillis(); statMonitor.handleResponse(ts - activityStamp); } return true; }
diff --git a/src/main/java/edu/uoc/pelp/actions/HomeAction.java b/src/main/java/edu/uoc/pelp/actions/HomeAction.java index cf856bb..5ef7a4c 100644 --- a/src/main/java/edu/uoc/pelp/actions/HomeAction.java +++ b/src/main/java/edu/uoc/pelp/actions/HomeAction.java @@ -1,532 +1,552 @@ package edu.uoc.pelp.actions; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.InterceptorRef; import org.apache.struts2.convention.annotation.InterceptorRefs; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.ResultPath; import org.apache.struts2.convention.annotation.Results; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import edu.uoc.pelp.bussines.UOC.UOCPelpBussines; import edu.uoc.pelp.bussines.UOC.vo.UOCClassroom; import edu.uoc.pelp.bussines.UOC.vo.UOCSubject; import edu.uoc.pelp.bussines.exception.AuthorizationException; import edu.uoc.pelp.bussines.exception.InvalidEngineException; import edu.uoc.pelp.bussines.vo.Activity; import edu.uoc.pelp.bussines.vo.DeliverDetail; import edu.uoc.pelp.bussines.vo.DeliverSummary; import edu.uoc.pelp.bussines.vo.UserInformation; import edu.uoc.pelp.engine.campus.UOC.CampusConnection; import edu.uoc.pelp.engine.campus.UOC.UserID; import edu.uoc.pelp.exception.ExecPelpException; import edu.uoc.pelp.exception.PelpException; import edu.uoc.pelp.test.tempClasses.LocalCampusConnection; /** * * Main action class for PeLP. Merged code from StudentAction and TeacherAction. * * @author oripolles * */ @ParentPackage(value = "default") @InterceptorRefs(value = { @InterceptorRef(value = "langInterceptor"), @InterceptorRef(value = "defaultStack") }) @Namespace("/") @ResultPath(value = "/") @Results({ @Result(name = "success", location = "WEB-INF/jsp/home.jsp"), @Result(name = "programming-environment", location = "WEB-INF/jsp/deliveries.jsp"), @Result(name="rsuccess", type="redirectAction", params = {"actionName" , "home"}), @Result(name="dinamic", type="json"), @Result(name = "filedown", type = "stream", params = { "contentType", "application/octet-stream", "inputName", "fileInputStream", "contentDisposition", "filename=\"${filename}\"" }), @Result(name="rprogramming-environment", type="redirectAction", params = {"actionName" , "home.html?activeTab=programming-environment"}) }) public class HomeAction extends ActionSupport { /** * */ private static final long serialVersionUID = 3165462908903079864L; public static final String TAB_DELIVERIES = "deliveries"; public static final String TAB_PROGRAMMING_ENVIROMENT = "programming-environment"; private UOCPelpBussines bUOC; private UOCSubject[] listSubjects; private UOCClassroom[] listClassroms; private Activity[] listActivity; private DeliverSummary[] listDeliverSummaries; private DeliverDetail[] listDeliverDetails; private int fileDim; private String s_assign; private String s_aula; private String s_activ; private String username; private String password; private String imageURL; private String fullName; private String activeTab; private boolean ajaxCall = true; private String selectorToLoad; private String idDelivers; private String idFile; private String filename; private InputStream fileInputStream; private String timeFile; private String maxDelivers; private String userId; private boolean teacher; @Override public String execute() throws Exception { //UOC API HttpServletRequest request = ServletActionContext.getRequest(); String token = (String) request.getSession().getAttribute("access_token"); if( token != null) { WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( ServletActionContext.getServletContext() ); CampusConnection campusConnection = (CampusConnection) context.getBean("lcctj"); campusConnection.setCampusSession(token); bUOC.setCampusConnection(campusConnection); } UserInformation userInfo = bUOC.getUserInformation(); if (userInfo != null) { listSubjects = bUOC.getUserSubjects(); if (s_assign != null) { String[] infoAssing = s_assign.split("_"); teacher = bUOC.isTeacher(new UOCSubject(infoAssing[0], infoAssing[2])); listClassroms = bUOC.getUserClassrooms(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null) { String[] infoAssing = s_assign.split("_"); listActivity = bUOC.getSubjectActivities(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null && s_activ != null && s_activ.length() > 0) { Activity objActivity = new Activity(); for (int j = 0; j < listActivity.length; j++) { if (listActivity[j].getIndex() == Integer.parseInt(s_activ)) { objActivity = listActivity[j]; } } String[] infoAssing = s_assign.split("_"); if(teacher){ UOCClassroom objClassroom = null; for(int i = 0;i<listClassroms.length;i++){ if(listClassroms[i].getIndex() == Integer.parseInt(s_aula)){ objClassroom = listClassroms[i]; } } //listDeliverDetails = bUOC.getAllClassroomDeliverDetails(objActivity, objClassroom); listDeliverDetails = bUOC.getLastClassroomDeliverDetails(objActivity, objClassroom); - if(listDeliverDetails!= null&&listDeliverDetails.length>0)maxDelivers = String.valueOf(listDeliverDetails[0].getMaxDelivers()); + if(listDeliverDetails!= null&&listDeliverDetails.length>0){ + int cont = 0; + Boolean exit=false; + while(!exit){ + if(listDeliverDetails[cont] != null){ + maxDelivers = String.valueOf(listDeliverDetails[cont].getMaxDelivers()); + exit=true; + } + cont++; + } + } //this.listStudents(listDeliverDetails); }else{ listDeliverDetails = bUOC.getUserDeliverDetails(new UOCSubject( infoAssing[0], infoAssing[2]), objActivity.getIndex()); - if(listDeliverDetails.length>0&& listDeliverDetails!= null)maxDelivers = String.valueOf(listDeliverDetails[0].getMaxDelivers()); + if(listDeliverDetails!= null && listDeliverDetails.length>0){ + int cont = 0; + Boolean exit=false; + while(!exit){ + if(listDeliverDetails[cont] != null){ + maxDelivers = String.valueOf(listDeliverDetails[cont].getMaxDelivers()); + exit=true; + } + cont++; + } + } } } imageURL = userInfo.getUserPhoto(); if(imageURL== null)imageURL = "img/user.png"; fullName = userInfo.getUserFullName(); } else { imageURL = null; fullName = null; } String toReturn = SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = TAB_PROGRAMMING_ENVIROMENT; } return toReturn; } public String combo() throws PelpException{ if (s_assign != null) { String[] infoAssing = s_assign.split("_"); teacher = bUOC.isTeacher(new UOCSubject(infoAssing[0], infoAssing[2])); listClassroms = bUOC.getUserClassrooms(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null) { String[] infoAssing = s_assign.split("_"); listActivity = bUOC.getSubjectActivities(new UOCSubject( infoAssing[0], infoAssing[2])); } return "dinamic"; } public String detaill() throws Exception, PelpException, AuthorizationException{ String[] infoAssing = s_assign.split("_"); UserID objUser = new UserID(userId); listDeliverDetails = bUOC.getUserDeliverDetails(objUser, infoAssing[0],infoAssing[2],Integer.parseInt(s_activ)); //(UserID userID, String semester, String subject, int activityIndex) return "dinamic"; } public String down() throws Exception { if (s_aula != null && s_aula.length() > 0 && s_assign != null && s_activ != null && s_activ.length() > 0) { String[] infoAssing = s_assign.split("_"); listActivity = bUOC.getSubjectActivities(new UOCSubject( infoAssing[0], infoAssing[2])); Activity objActivity = new Activity(); for (int j = 0; j < listActivity.length; j++) { if (listActivity[j].getIndex() == Integer.parseInt(s_activ)) { objActivity = listActivity[j]; } } // Miramos si tiene userId, entonces la llamada es diferente if(userId!=null){ UserID objUser = new UserID(userId); listDeliverDetails = bUOC.getUserDeliverDetails(objUser, infoAssing[0],infoAssing[2],Integer.parseInt(s_activ)); }else{ listDeliverDetails = bUOC.getUserDeliverDetails(new UOCSubject(infoAssing[0], infoAssing[2]), objActivity.getIndex()); } String urlpath = listDeliverDetails[Integer.parseInt(idDelivers)].getDeliverFiles()[Integer.parseInt(idFile)].getAbsolutePath(); File file = new File(urlpath); fileInputStream = new FileInputStream(file); filename = listDeliverDetails[Integer.parseInt(idDelivers)].getDeliverFiles()[Integer.parseInt(idFile)].getRelativePath(); } return "filedown"; } public String logout() throws PelpException { /*HttpServletRequest request = ServletActionContext.getRequest(); request.getSession().setAttribute("authUOC", "close"); bUOC.setCampusConnection(new CampusConnection()); bUOC.logout(); String toReturn = 'r'+SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = 'r'+TAB_PROGRAMMING_ENVIROMENT; } return toReturn; */ //bUOC.logout(); HttpServletRequest request = ServletActionContext.getRequest(); request.getSession().setAttribute("authUOC", "close"); LocalCampusConnection _campusConnection = new LocalCampusConnection(); // Add the register to the admin database to give administration rights _campusConnection.setProfile("none"); bUOC.setCampusConnection(_campusConnection); String toReturn = 'r'+SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = 'r'+TAB_PROGRAMMING_ENVIROMENT; } return toReturn; } public String authLocal() throws Exception { //FIXME Miramos Si es estudiante , professor i dependiendo usaremos uno o otro LocalCampusConnection _campusConnection = new LocalCampusConnection(); _campusConnection.setProfile(username); bUOC.setCampusConnection(_campusConnection); String toReturn = 'r'+SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = 'r'+TAB_PROGRAMMING_ENVIROMENT; } return toReturn; } public String auth() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); request.getSession().setAttribute("authUOC", "request"); if(bUOC != null && bUOC.getUserInformation()!=null){ String lang = bUOC.getUserInformation().getLanguage(); System.out.println("IDIOMA USUARIO: "+lang); Map session = ActionContext.getContext().getSession(); if(lang.equals("ca")){ session.put("WW_TRANS_I18N_LOCALE",new java.util.Locale("ca")); Locale locale = new Locale("ca", "ES"); session.put("org.apache.tiles.LOCALE", locale); }else if(lang.equals("es")){ session.put("WW_TRANS_I18N_LOCALE",new java.util.Locale("es")); Locale locale = new Locale("es", "ES"); session.put("org.apache.tiles.LOCALE", locale); }else if(lang.equals("en")){ session.put("WW_TRANS_I18N_LOCALE",new java.util.Locale("en")); Locale locale = new Locale("en", "UK"); session.put("org.apache.tiles.LOCALE", locale); } } String toReturn = 'r'+SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = 'r'+TAB_PROGRAMMING_ENVIROMENT; } return toReturn; } public UOCPelpBussines getbUOC() { return bUOC; } public void setbUOC(UOCPelpBussines bUOC) { this.bUOC = bUOC; } public UOCSubject[] getListSubjects() { return listSubjects; } public void setListSubjects(UOCSubject[] listSubjects) { this.listSubjects = listSubjects; } public UOCClassroom[] getListClassroms() { return listClassroms; } public void setListClassroms(UOCClassroom[] listClassroms) { this.listClassroms = listClassroms; } public Activity[] getListActivity() { return listActivity; } public void setListActivity(Activity[] listActivity) { this.listActivity = listActivity; } public DeliverSummary[] getListDeliverSummaries() { return listDeliverSummaries; } public void setListDeliverSummaries(DeliverSummary[] listDeliverSummaries) { this.listDeliverSummaries = listDeliverSummaries; } public DeliverDetail[] getListDeliverDetails() { return listDeliverDetails; } public void setListDeliverDetails(DeliverDetail[] listDeliverDetails) { this.listDeliverDetails = listDeliverDetails; } public String getS_assign() { return s_assign; } public void setS_assign(String s_assign) { this.s_assign = s_assign; } public String getS_aula() { return s_aula; } public void setS_aula(String s_aula) { this.s_aula = s_aula; } public String getS_activ() { return s_activ; } public void setS_activ(String s_activ) { this.s_activ = s_activ; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getImageURL() { return imageURL; } public void setImageURL(String imageURL) { this.imageURL = imageURL; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getActiveTab() { return activeTab; } public void setActiveTab(String activeTab) { this.activeTab = activeTab; } public boolean isAjaxCall() { return ajaxCall; } public void setAjaxCall(boolean ajaxCall) { this.ajaxCall = ajaxCall; } public String getSelectorToLoad() { return selectorToLoad; } public void setSelectorToLoad(String selectorToLoad) { this.selectorToLoad = selectorToLoad; } public boolean isTeacher() { return teacher; } public void setTeacher(boolean teacher) { this.teacher = teacher; } public String getIdDelivers() { return idDelivers; } public void setIdDelivers(String idDelivers) { this.idDelivers = idDelivers; } public String getIdFile() { return idFile; } public void setIdFile(String idFile) { this.idFile = idFile; } public InputStream getFileInputStream() { return fileInputStream; } public void setFileInputStream(InputStream fileInputStream) { this.fileInputStream = fileInputStream; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public int getFileDim() { return fileDim; } public void setFileDim(int fileDim) { this.fileDim = fileDim; } public String getTimeFile() { return timeFile; } public void setTimeFile(String timeFile) { this.timeFile = timeFile; } public String getMaxDelivers() { return maxDelivers; } public void setMaxDelivers(String maxDelivers) { this.maxDelivers = maxDelivers; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
false
true
public String execute() throws Exception { //UOC API HttpServletRequest request = ServletActionContext.getRequest(); String token = (String) request.getSession().getAttribute("access_token"); if( token != null) { WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( ServletActionContext.getServletContext() ); CampusConnection campusConnection = (CampusConnection) context.getBean("lcctj"); campusConnection.setCampusSession(token); bUOC.setCampusConnection(campusConnection); } UserInformation userInfo = bUOC.getUserInformation(); if (userInfo != null) { listSubjects = bUOC.getUserSubjects(); if (s_assign != null) { String[] infoAssing = s_assign.split("_"); teacher = bUOC.isTeacher(new UOCSubject(infoAssing[0], infoAssing[2])); listClassroms = bUOC.getUserClassrooms(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null) { String[] infoAssing = s_assign.split("_"); listActivity = bUOC.getSubjectActivities(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null && s_activ != null && s_activ.length() > 0) { Activity objActivity = new Activity(); for (int j = 0; j < listActivity.length; j++) { if (listActivity[j].getIndex() == Integer.parseInt(s_activ)) { objActivity = listActivity[j]; } } String[] infoAssing = s_assign.split("_"); if(teacher){ UOCClassroom objClassroom = null; for(int i = 0;i<listClassroms.length;i++){ if(listClassroms[i].getIndex() == Integer.parseInt(s_aula)){ objClassroom = listClassroms[i]; } } //listDeliverDetails = bUOC.getAllClassroomDeliverDetails(objActivity, objClassroom); listDeliverDetails = bUOC.getLastClassroomDeliverDetails(objActivity, objClassroom); if(listDeliverDetails!= null&&listDeliverDetails.length>0)maxDelivers = String.valueOf(listDeliverDetails[0].getMaxDelivers()); //this.listStudents(listDeliverDetails); }else{ listDeliverDetails = bUOC.getUserDeliverDetails(new UOCSubject( infoAssing[0], infoAssing[2]), objActivity.getIndex()); if(listDeliverDetails.length>0&& listDeliverDetails!= null)maxDelivers = String.valueOf(listDeliverDetails[0].getMaxDelivers()); } } imageURL = userInfo.getUserPhoto(); if(imageURL== null)imageURL = "img/user.png"; fullName = userInfo.getUserFullName(); } else { imageURL = null; fullName = null; } String toReturn = SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = TAB_PROGRAMMING_ENVIROMENT; } return toReturn; }
public String execute() throws Exception { //UOC API HttpServletRequest request = ServletActionContext.getRequest(); String token = (String) request.getSession().getAttribute("access_token"); if( token != null) { WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext( ServletActionContext.getServletContext() ); CampusConnection campusConnection = (CampusConnection) context.getBean("lcctj"); campusConnection.setCampusSession(token); bUOC.setCampusConnection(campusConnection); } UserInformation userInfo = bUOC.getUserInformation(); if (userInfo != null) { listSubjects = bUOC.getUserSubjects(); if (s_assign != null) { String[] infoAssing = s_assign.split("_"); teacher = bUOC.isTeacher(new UOCSubject(infoAssing[0], infoAssing[2])); listClassroms = bUOC.getUserClassrooms(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null) { String[] infoAssing = s_assign.split("_"); listActivity = bUOC.getSubjectActivities(new UOCSubject( infoAssing[0], infoAssing[2])); } if (s_aula != null && s_aula.length() > 0 && s_assign != null && s_activ != null && s_activ.length() > 0) { Activity objActivity = new Activity(); for (int j = 0; j < listActivity.length; j++) { if (listActivity[j].getIndex() == Integer.parseInt(s_activ)) { objActivity = listActivity[j]; } } String[] infoAssing = s_assign.split("_"); if(teacher){ UOCClassroom objClassroom = null; for(int i = 0;i<listClassroms.length;i++){ if(listClassroms[i].getIndex() == Integer.parseInt(s_aula)){ objClassroom = listClassroms[i]; } } //listDeliverDetails = bUOC.getAllClassroomDeliverDetails(objActivity, objClassroom); listDeliverDetails = bUOC.getLastClassroomDeliverDetails(objActivity, objClassroom); if(listDeliverDetails!= null&&listDeliverDetails.length>0){ int cont = 0; Boolean exit=false; while(!exit){ if(listDeliverDetails[cont] != null){ maxDelivers = String.valueOf(listDeliverDetails[cont].getMaxDelivers()); exit=true; } cont++; } } //this.listStudents(listDeliverDetails); }else{ listDeliverDetails = bUOC.getUserDeliverDetails(new UOCSubject( infoAssing[0], infoAssing[2]), objActivity.getIndex()); if(listDeliverDetails!= null && listDeliverDetails.length>0){ int cont = 0; Boolean exit=false; while(!exit){ if(listDeliverDetails[cont] != null){ maxDelivers = String.valueOf(listDeliverDetails[cont].getMaxDelivers()); exit=true; } cont++; } } } } imageURL = userInfo.getUserPhoto(); if(imageURL== null)imageURL = "img/user.png"; fullName = userInfo.getUserFullName(); } else { imageURL = null; fullName = null; } String toReturn = SUCCESS; if (TAB_PROGRAMMING_ENVIROMENT.equals(activeTab)) { toReturn = TAB_PROGRAMMING_ENVIROMENT; } return toReturn; }
diff --git a/core/src/java/liquibase/database/sql/DropIndexStatement.java b/core/src/java/liquibase/database/sql/DropIndexStatement.java index e68d10cd..03b9ed0f 100644 --- a/core/src/java/liquibase/database/sql/DropIndexStatement.java +++ b/core/src/java/liquibase/database/sql/DropIndexStatement.java @@ -1,55 +1,61 @@ package liquibase.database.sql; import liquibase.database.Database; import liquibase.database.MSSQLDatabase; import liquibase.database.MySQLDatabase; import liquibase.database.OracleDatabase; import liquibase.exception.StatementNotSupportedOnDatabaseException; public class DropIndexStatement implements SqlStatement { private String indexName; private String tableSchemaName; private String tableName; public DropIndexStatement(String indexName, String tableSchemaName, String tableName) { this.tableSchemaName = tableSchemaName; this.indexName = indexName; this.tableName = tableName; } public String getTableSchemaName() { return tableSchemaName; } public String getIndexName() { return indexName; } public String getTableName() { return tableName; } public String getSqlStatement(Database database) throws StatementNotSupportedOnDatabaseException { if (getTableSchemaName() != null && !database.supportsSchemas()) { throw new StatementNotSupportedOnDatabaseException("Database does not support schemas", this, database); } if (database instanceof MySQLDatabase) { + if (getTableName() == null) { + throw new StatementNotSupportedOnDatabaseException("tableName is required", this, database); + } return "DROP INDEX " +getIndexName() + " ON " + database.escapeTableName(getTableSchemaName(), getTableName()); } else if (database instanceof MSSQLDatabase) { + if (getTableName() == null) { + throw new StatementNotSupportedOnDatabaseException("tableName is required", this, database); + } return "DROP INDEX " + database.escapeTableName(getTableSchemaName(), getTableName()) + "." + getIndexName(); } else if (database instanceof OracleDatabase) { return "DROP INDEX " + getIndexName(); } return "DROP INDEX " + getIndexName(); } public String getEndDelimiter(Database database) { return ";"; } public boolean supportsDatabase(Database database) { return true; } }
false
true
public String getSqlStatement(Database database) throws StatementNotSupportedOnDatabaseException { if (getTableSchemaName() != null && !database.supportsSchemas()) { throw new StatementNotSupportedOnDatabaseException("Database does not support schemas", this, database); } if (database instanceof MySQLDatabase) { return "DROP INDEX " +getIndexName() + " ON " + database.escapeTableName(getTableSchemaName(), getTableName()); } else if (database instanceof MSSQLDatabase) { return "DROP INDEX " + database.escapeTableName(getTableSchemaName(), getTableName()) + "." + getIndexName(); } else if (database instanceof OracleDatabase) { return "DROP INDEX " + getIndexName(); } return "DROP INDEX " + getIndexName(); }
public String getSqlStatement(Database database) throws StatementNotSupportedOnDatabaseException { if (getTableSchemaName() != null && !database.supportsSchemas()) { throw new StatementNotSupportedOnDatabaseException("Database does not support schemas", this, database); } if (database instanceof MySQLDatabase) { if (getTableName() == null) { throw new StatementNotSupportedOnDatabaseException("tableName is required", this, database); } return "DROP INDEX " +getIndexName() + " ON " + database.escapeTableName(getTableSchemaName(), getTableName()); } else if (database instanceof MSSQLDatabase) { if (getTableName() == null) { throw new StatementNotSupportedOnDatabaseException("tableName is required", this, database); } return "DROP INDEX " + database.escapeTableName(getTableSchemaName(), getTableName()) + "." + getIndexName(); } else if (database instanceof OracleDatabase) { return "DROP INDEX " + getIndexName(); } return "DROP INDEX " + getIndexName(); }
diff --git a/src/org/rubyforge/debugcommons/ReadersSupport.java b/src/org/rubyforge/debugcommons/ReadersSupport.java index a8048b2..211c0cc 100644 --- a/src/org/rubyforge/debugcommons/ReadersSupport.java +++ b/src/org/rubyforge/debugcommons/ReadersSupport.java @@ -1,238 +1,240 @@ package org.rubyforge.debugcommons; import org.rubyforge.debugcommons.reader.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.rubyforge.debugcommons.model.RubyFrameInfo; import org.rubyforge.debugcommons.model.SuspensionPoint; import org.rubyforge.debugcommons.model.RubyThreadInfo; import org.rubyforge.debugcommons.model.RubyVariableInfo; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; final class ReadersSupport { private static final String BREAKPOINT_ELEMENT = "breakpoint"; private static final String SUSPENDED_ELEMENT = "suspended"; private static final String ERROR_ELEMENT = "error"; private static final String MESSAGE_ELEMENT = "message"; private static final String BREAKPOINT_ADDED_ELEMENT = "breakpointAdded"; private static final String BREAKPOINT_DELETED_ELEMENT = "breakpointDeleted"; private static final String THREADS_ELEMENT = "threads"; private static final String FRAMES_ELEMENT = "frames"; private static final String VARIABLES_ELEMENT = "variables"; private static final String PROCESSING_EXCEPTION_ELEMENT = "processingException"; private static final String RUBY_DEBUG_PROMPT = "PROMPT"; /** * Reading timeout until giving up when polling information from socket * communication. */ private final long timeout; private final BlockingQueue<RubyThreadInfo[]> threads; private final BlockingQueue<RubyFrameInfo[]> frames; private final BlockingQueue<RubyVariableInfo[]> variables; private final BlockingQueue<SuspensionPoint> suspensions; private final BlockingQueue<Integer> addedBreakpoints; private final BlockingQueue<Integer> removedBreakpoints; /** * @param timeout reading timeout until giving up when polling information * from socket communication. */ ReadersSupport(final long timeout) throws RubyDebuggerException { this.timeout = timeout; this.threads = new LinkedBlockingQueue<RubyThreadInfo[]>(); this.frames = new LinkedBlockingQueue<RubyFrameInfo[]>(); this.variables = new LinkedBlockingQueue<RubyVariableInfo[]>(); this.suspensions = new LinkedBlockingQueue<SuspensionPoint>(); this.addedBreakpoints = new LinkedBlockingQueue<Integer>(); this.removedBreakpoints = new LinkedBlockingQueue<Integer>(); } void startCommandLoop(final Socket commandSocket) throws RubyDebuggerException { startLoop(commandSocket, "command loop"); } private void startLoop(final Socket socket, final String name) throws RubyDebuggerException { try { new XPPLoop(getXpp(socket), ReadersSupport.class + " " + name).start(); } catch (IOException e) { throw new RubyDebuggerException(e); } catch (XmlPullParserException e) { throw new RubyDebuggerException(e); } } private void startXPPLoop(final XmlPullParser xpp) throws XmlPullParserException, IOException { int eventType = xpp.getEventType(); do { if (eventType == XmlPullParser.START_TAG) { processElement(xpp); } else if (eventType == XmlPullParser.END_TAG) { assert false : "Unexpected state: end tag " + xpp.getName(); } else if (eventType == XmlPullParser.TEXT) { if (xpp.getText().contains(RUBY_DEBUG_PROMPT)) { Util.finest("got ruby-debug prompt message"); } else { assert false : "Unexpected state: text " + xpp.getText(); } } else if (eventType == XmlPullParser.START_DOCUMENT) { // OK, first cycle, do nothing. } else { assert false : "Unexpected state: " + eventType; } eventType = xpp.next(); } while (eventType != XmlPullParser.END_DOCUMENT); } private void processElement(final XmlPullParser xpp) throws IOException, XmlPullParserException { String element = xpp.getName(); if (BREAKPOINT_ADDED_ELEMENT.equals(element)) { addedBreakpoints.add(BreakpointAddedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_DELETED_ELEMENT.equals(element)) { removedBreakpoints.add(BreakpointDeletedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); } else if (SUSPENDED_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); - } else if (ERROR_ELEMENT.equals(element) || MESSAGE_ELEMENT.equals(element)) { + } else if (ERROR_ELEMENT.equals(element)) { + Util.warning(ErrorReader.readMessage(xpp)); + } else if (MESSAGE_ELEMENT.equals(element)) { Util.info(ErrorReader.readMessage(xpp)); } else if (THREADS_ELEMENT.equals(element)) { threads.add(ThreadInfoReader.readThreads(xpp)); } else if (FRAMES_ELEMENT.equals(element)) { frames.add(FramesReader.readFrames(xpp)); } else if (VARIABLES_ELEMENT.equals(element)) { variables.add(VariablesReader.readVariables(xpp)); } else if (PROCESSING_EXCEPTION_ELEMENT.equals(element)) { VariablesReader.logProcessingException(xpp); variables.add(new RubyVariableInfo[0]); } else { assert false : "Unexpected element: " + element; } } private <T> T[] readInfo(BlockingQueue<T[]> queue) throws RubyDebuggerException { try { T[] result = queue.poll(timeout, TimeUnit.SECONDS); if (result == null) { throw new RubyDebuggerException("Unable to read information in the specified timeout [" + timeout + "s]"); } else { return result; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RubyDebuggerException("Interruped during reading information " + queue.getClass(), ex); } } RubyThreadInfo[] readThreads() throws RubyDebuggerException { return readInfo(threads); } RubyFrameInfo[] readFrames() throws RubyDebuggerException { return readInfo(frames); } RubyVariableInfo[] readVariables() throws RubyDebuggerException { return readInfo(variables); } int readAddedBreakpointNo() throws RubyDebuggerException { try { Integer breakpointNo = addedBreakpoints.poll(timeout, TimeUnit.SECONDS); if (breakpointNo == null) { throw new RubyDebuggerException("Unable to read added breakpoint number in the specified timeout [" + timeout + "s]"); } else { return breakpointNo; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RubyDebuggerException("Interruped during reading added breakpoint number", ex); } } int waitForRemovedBreakpoint(int breakpointID) throws RubyDebuggerException { try { Integer removedID = removedBreakpoints.poll(timeout, TimeUnit.SECONDS); if (removedID == null) { throw new RubyDebuggerException("Unable to read breakpoint number of the removed breakpoint (" + breakpointID + ") in the specified timeout [" + timeout + "s]"); } else if (removedID != breakpointID) { throw new RubyDebuggerException("Unexpected breakpoint removed. " + "Received id: " + removedID + ", expected: " + breakpointID); } else { return removedID; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RubyDebuggerException("Interruped during reading added breakpoint number", ex); } } SuspensionPoint readSuspension() { try { return suspensions.take(); } catch (InterruptedException ex) { Util.severe("Interruped during reading suspension point", ex); return null; } } private static XmlPullParser getXpp(Socket socket) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance( "org.kxml2.io.KXmlParser,org.kxml2.io.KXmlSerializer", null); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(new BufferedReader(new InputStreamReader(socket.getInputStream()))); return xpp; } private class XPPLoop extends Thread { final XmlPullParser xpp; XPPLoop(final XmlPullParser xpp, final String loopName) { super(loopName); this.xpp = xpp; } @Override public void run() { try { Util.fine("Starting ReadersSupport readloop: " + getName()); startXPPLoop(xpp); Util.fine("ReadersSupport readloop [" + getName() + "] successfully finished."); } catch (IOException e) { // Debugger is just killed. So this is currently more or less // expected behaviour. // - no XmlPullParser.END_DOCUMENT is sent // - incorectly handling finishing of the session in the backends Util.fine("SocketException. Loop [" + getName() + "]: " + e.getMessage()); } catch (XmlPullParserException e) { Util.severe("Exception during ReadersSupport loop [" + getName() + ']', e); } finally { suspensions.add(SuspensionPoint.END); try { Thread.sleep(1000); // Avoid Commodification Exceptions } catch (InterruptedException e) { Util.severe("Readers loop interrupted", e); } } } } }
true
true
private void processElement(final XmlPullParser xpp) throws IOException, XmlPullParserException { String element = xpp.getName(); if (BREAKPOINT_ADDED_ELEMENT.equals(element)) { addedBreakpoints.add(BreakpointAddedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_DELETED_ELEMENT.equals(element)) { removedBreakpoints.add(BreakpointDeletedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); } else if (SUSPENDED_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); } else if (ERROR_ELEMENT.equals(element) || MESSAGE_ELEMENT.equals(element)) { Util.info(ErrorReader.readMessage(xpp)); } else if (THREADS_ELEMENT.equals(element)) { threads.add(ThreadInfoReader.readThreads(xpp)); } else if (FRAMES_ELEMENT.equals(element)) { frames.add(FramesReader.readFrames(xpp)); } else if (VARIABLES_ELEMENT.equals(element)) { variables.add(VariablesReader.readVariables(xpp)); } else if (PROCESSING_EXCEPTION_ELEMENT.equals(element)) { VariablesReader.logProcessingException(xpp); variables.add(new RubyVariableInfo[0]); } else { assert false : "Unexpected element: " + element; } }
private void processElement(final XmlPullParser xpp) throws IOException, XmlPullParserException { String element = xpp.getName(); if (BREAKPOINT_ADDED_ELEMENT.equals(element)) { addedBreakpoints.add(BreakpointAddedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_DELETED_ELEMENT.equals(element)) { removedBreakpoints.add(BreakpointDeletedReader.readBreakpointNo(xpp)); } else if (BREAKPOINT_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); } else if (SUSPENDED_ELEMENT.equals(element)) { SuspensionPoint sp = SuspensionReader.readSuspension(xpp); suspensions.add(sp); } else if (ERROR_ELEMENT.equals(element)) { Util.warning(ErrorReader.readMessage(xpp)); } else if (MESSAGE_ELEMENT.equals(element)) { Util.info(ErrorReader.readMessage(xpp)); } else if (THREADS_ELEMENT.equals(element)) { threads.add(ThreadInfoReader.readThreads(xpp)); } else if (FRAMES_ELEMENT.equals(element)) { frames.add(FramesReader.readFrames(xpp)); } else if (VARIABLES_ELEMENT.equals(element)) { variables.add(VariablesReader.readVariables(xpp)); } else if (PROCESSING_EXCEPTION_ELEMENT.equals(element)) { VariablesReader.logProcessingException(xpp); variables.add(new RubyVariableInfo[0]); } else { assert false : "Unexpected element: " + element; } }
diff --git a/com.vainolo.phd.opm.interpreter/src/com/vainolo/phd/opm/interpreter/OPMProcessInstanceFactoryImpl.java b/com.vainolo.phd.opm.interpreter/src/com/vainolo/phd/opm/interpreter/OPMProcessInstanceFactoryImpl.java index 4f777a7..b9e2ff1 100644 --- a/com.vainolo.phd.opm.interpreter/src/com/vainolo/phd/opm/interpreter/OPMProcessInstanceFactoryImpl.java +++ b/com.vainolo.phd.opm.interpreter/src/com/vainolo/phd/opm/interpreter/OPMProcessInstanceFactoryImpl.java @@ -1,53 +1,52 @@ /******************************************************************************* * Copyright (c) 2012 Arieh 'Vainolo' Bibliowicz * You can use this code for educational purposes. For any other uses * please contact me: [email protected] *******************************************************************************/ package com.vainolo.phd.opm.interpreter; import com.vainolo.phd.opm.interpreter.builtin.OPMAddProcessInstance; import com.vainolo.phd.opm.interpreter.builtin.OPMInputProcessInstance; import com.vainolo.phd.opm.interpreter.builtin.OPMOutputProcessInstance; import com.vainolo.phd.opm.model.OPMProcessKind; public enum OPMProcessInstanceFactoryImpl implements OPMProcessInstanceFactory { INSTANCE; @Override public OPMProcessInstance createProcessInstance(final String processName, final OPMProcessKind kind) { - // Create process instance. OPMProcessInstance processInstance; switch(kind) { case BUILT_IN: processInstance = createBuildInProcess(processName); break; case COMPOUND: processInstance = new OPMCompoundProcessInstance(processName); break; case CONCEPTUAL: throw new UnsupportedOperationException("Conceptual processes are not supported yet."); case JAVA: throw new UnsupportedOperationException("Java processes are not supported yet."); default: throw new IllegalStateException("Received unexpected OPMProcessKind " + kind.getName()); } return processInstance; } private OPMProcessInstance createBuildInProcess(final String processName) { OPMProcessInstance processInstance; if(processName.equals("Input")) processInstance = new OPMInputProcessInstance(); else if(processName.equals("Output")) processInstance = new OPMOutputProcessInstance(); else if(processName.equals("Add")) processInstance = new OPMAddProcessInstance(); else throw new IllegalStateException("Tried to create unexistent build-in process " + processName); return processInstance; } }
true
true
public OPMProcessInstance createProcessInstance(final String processName, final OPMProcessKind kind) { // Create process instance. OPMProcessInstance processInstance; switch(kind) { case BUILT_IN: processInstance = createBuildInProcess(processName); break; case COMPOUND: processInstance = new OPMCompoundProcessInstance(processName); break; case CONCEPTUAL: throw new UnsupportedOperationException("Conceptual processes are not supported yet."); case JAVA: throw new UnsupportedOperationException("Java processes are not supported yet."); default: throw new IllegalStateException("Received unexpected OPMProcessKind " + kind.getName()); } return processInstance; }
public OPMProcessInstance createProcessInstance(final String processName, final OPMProcessKind kind) { OPMProcessInstance processInstance; switch(kind) { case BUILT_IN: processInstance = createBuildInProcess(processName); break; case COMPOUND: processInstance = new OPMCompoundProcessInstance(processName); break; case CONCEPTUAL: throw new UnsupportedOperationException("Conceptual processes are not supported yet."); case JAVA: throw new UnsupportedOperationException("Java processes are not supported yet."); default: throw new IllegalStateException("Received unexpected OPMProcessKind " + kind.getName()); } return processInstance; }
diff --git a/contrib/src/java/org/apache/tapestry/contrib/form/CheckBoxMultiplePropertySelectionRenderer.java b/contrib/src/java/org/apache/tapestry/contrib/form/CheckBoxMultiplePropertySelectionRenderer.java index b56184bb1..a9dc586b6 100644 --- a/contrib/src/java/org/apache/tapestry/contrib/form/CheckBoxMultiplePropertySelectionRenderer.java +++ b/contrib/src/java/org/apache/tapestry/contrib/form/CheckBoxMultiplePropertySelectionRenderer.java @@ -1,102 +1,107 @@ // Copyright 2004, 2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry.contrib.form; import org.apache.tapestry.IMarkupWriter; import org.apache.tapestry.IRequestCycle; import org.apache.tapestry.form.IPropertySelectionModel; /** * Implementation of {@link IMultiplePropertySelectionRenderer} that * produces a table of checkbox (&lt;input type=checkbox&gt;) elements. * * @author Sanjay Munjal * */ public class CheckBoxMultiplePropertySelectionRenderer implements IMultiplePropertySelectionRenderer { /** * Writes the &lt;table&gt; element. * **/ public void beginRender( MultiplePropertySelection component, IMarkupWriter writer, IRequestCycle cycle) { writer.begin("table"); writer.attribute("border", 0); writer.attribute("cellpadding", 0); writer.attribute("cellspacing", 2); } /** * Closes the &lt;table&gt; element. * **/ public void endRender( MultiplePropertySelection component, IMarkupWriter writer, IRequestCycle cycle) { writer.end(); // <table> } /** * Writes a row of the table. The table contains two cells; the first is the checkbox, * the second is the label for the checkbox. * **/ public void renderOption( MultiplePropertySelection component, IMarkupWriter writer, IRequestCycle cycle, IPropertySelectionModel model, Object option, int index, boolean selected) { writer.begin("tr"); writer.begin("td"); writer.beginEmpty("input"); writer.attribute("type", "checkbox"); writer.attribute("name", component.getName()); + String id = component.getName() + "." +model.getValue(index); + writer.attribute("id", id); writer.attribute("value", model.getValue(index)); if (component.isDisabled()) writer.attribute("disabled", "disabled"); if (selected) writer.attribute("checked", "checked"); writer.end(); // <td> writer.println(); writer.begin("td"); + writer.begin("label"); + writer.attribute("for", id); writer.print(model.getLabel(index)); + writer.end(); // <label> writer.end(); // <td> writer.end(); // <tr> writer.println(); } }
false
true
public void renderOption( MultiplePropertySelection component, IMarkupWriter writer, IRequestCycle cycle, IPropertySelectionModel model, Object option, int index, boolean selected) { writer.begin("tr"); writer.begin("td"); writer.beginEmpty("input"); writer.attribute("type", "checkbox"); writer.attribute("name", component.getName()); writer.attribute("value", model.getValue(index)); if (component.isDisabled()) writer.attribute("disabled", "disabled"); if (selected) writer.attribute("checked", "checked"); writer.end(); // <td> writer.println(); writer.begin("td"); writer.print(model.getLabel(index)); writer.end(); // <td> writer.end(); // <tr> writer.println(); }
public void renderOption( MultiplePropertySelection component, IMarkupWriter writer, IRequestCycle cycle, IPropertySelectionModel model, Object option, int index, boolean selected) { writer.begin("tr"); writer.begin("td"); writer.beginEmpty("input"); writer.attribute("type", "checkbox"); writer.attribute("name", component.getName()); String id = component.getName() + "." +model.getValue(index); writer.attribute("id", id); writer.attribute("value", model.getValue(index)); if (component.isDisabled()) writer.attribute("disabled", "disabled"); if (selected) writer.attribute("checked", "checked"); writer.end(); // <td> writer.println(); writer.begin("td"); writer.begin("label"); writer.attribute("for", id); writer.print(model.getLabel(index)); writer.end(); // <label> writer.end(); // <td> writer.end(); // <tr> writer.println(); }
diff --git a/homework13/Test.java b/homework13/Test.java index f99eb74..6ff7369 100644 --- a/homework13/Test.java +++ b/homework13/Test.java @@ -1,25 +1,25 @@ public class Test { public static void main( String[] args ) { Shape[] shapes = new Shape[4]; shapes[0] = new Circle( 22, 88, "Circle", 4 ); shapes[1] = new Square( 71, 96, "Square", 10 ); shapes[2] = new Sphere( 8, 89, "Sphere", 2 ); shapes[3] = new Cube( 79, 61, "Cube", 8 ); for ( Shape s : shapes ) { System.out.println( s ); if ( s instanceof TwoDimensionalShape ) { - System.out.println( s.getArea() ); + System.out.println( ( (TwoDimensionalShape)s ).getArea() ); } else if ( s instanceof ThreeDimensionalShape ) { - System.out.println( s.getArea() ); - System.out.println( s.getVolume() ); + System.out.println( ( (ThreeDimensionalShape)s ).getArea() ); + System.out.println( ( (ThreeDimensionalShape)s ).getVolume() ); } } } }
false
true
public static void main( String[] args ) { Shape[] shapes = new Shape[4]; shapes[0] = new Circle( 22, 88, "Circle", 4 ); shapes[1] = new Square( 71, 96, "Square", 10 ); shapes[2] = new Sphere( 8, 89, "Sphere", 2 ); shapes[3] = new Cube( 79, 61, "Cube", 8 ); for ( Shape s : shapes ) { System.out.println( s ); if ( s instanceof TwoDimensionalShape ) { System.out.println( s.getArea() ); } else if ( s instanceof ThreeDimensionalShape ) { System.out.println( s.getArea() ); System.out.println( s.getVolume() ); } } }
public static void main( String[] args ) { Shape[] shapes = new Shape[4]; shapes[0] = new Circle( 22, 88, "Circle", 4 ); shapes[1] = new Square( 71, 96, "Square", 10 ); shapes[2] = new Sphere( 8, 89, "Sphere", 2 ); shapes[3] = new Cube( 79, 61, "Cube", 8 ); for ( Shape s : shapes ) { System.out.println( s ); if ( s instanceof TwoDimensionalShape ) { System.out.println( ( (TwoDimensionalShape)s ).getArea() ); } else if ( s instanceof ThreeDimensionalShape ) { System.out.println( ( (ThreeDimensionalShape)s ).getArea() ); System.out.println( ( (ThreeDimensionalShape)s ).getVolume() ); } } }
diff --git a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java index 66520c919..fc35be6d2 100644 --- a/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java +++ b/activemq-unit-tests/src/test/java/org/apache/activemq/broker/region/group/MessageGroupHashBucketTest.java @@ -1,30 +1,30 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker.region.group; /** * * */ public class MessageGroupHashBucketTest extends MessageGroupMapTest { protected MessageGroupMap createMessageGroupMap() { - return new MessageGroupHashBucket(1024); + return new MessageGroupHashBucket(1024, 64); } }
true
true
protected MessageGroupMap createMessageGroupMap() { return new MessageGroupHashBucket(1024); }
protected MessageGroupMap createMessageGroupMap() { return new MessageGroupHashBucket(1024, 64); }
diff --git a/components/ome-io/src/loci/ome/io/OmeroReader.java b/components/ome-io/src/loci/ome/io/OmeroReader.java index c71b9eea2..e4c653700 100644 --- a/components/ome-io/src/loci/ome/io/OmeroReader.java +++ b/components/ome-io/src/loci/ome/io/OmeroReader.java @@ -1,374 +1,375 @@ // // OmeroReader.java // /* OME database I/O package for communicating with OME and OMERO servers. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden and Philip Huettl. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.ome.io; import Glacier2.CannotCreateSessionException; import Glacier2.PermissionDeniedException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.List; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.tools.ImageInfo; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import omero.RDouble; import omero.RInt; import omero.RString; import omero.RTime; import omero.ServerError; import omero.api.GatewayPrx; import omero.api.RawPixelsStorePrx; import omero.api.ServiceFactoryPrx; import omero.model.Channel; import omero.model.Image; import omero.model.LogicalChannel; import omero.model.Pixels; /** * Implementation of {@link loci.formats.IFormatReader} * for use in export from an OMERO Beta 4.2.x database. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/ome-io/src/loci/ome/io/OmeroReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/ome-io/src/loci/ome/io/OmeroReader.java;hb=HEAD">Gitweb</a></dd></dl> */ public class OmeroReader extends FormatReader { // -- Constants -- public static final int DEFAULT_PORT = 4064; // -- Fields -- private String server; private String username; private String password; private int thePort = DEFAULT_PORT; private omero.client client; private RawPixelsStorePrx store; private Image img; private Pixels pix; // -- Constructors -- public OmeroReader() { super("OMERO", "*"); } // -- OmeroReader methods -- public void setServer(String server) { this.server = server; } public void setPort(int port) { thePort = port; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } // -- IFormatReader methods -- @Override public boolean isThisType(String name, boolean open) { return name.startsWith("omero:"); } @Override public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); FormatTools.checkBufferSize(this, buf.length, w, h); final int[] zct = FormatTools.getZCTCoords(this, no); final byte[] plane; try { plane = store.getPlane(zct[0], zct[1], zct[2]); } catch (ServerError e) { throw new FormatException(e); } RandomAccessInputStream s = new RandomAccessInputStream(plane); readPlane(s, x, y, w, h, buf); s.close(); return buf; } @Override public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly && client != null) { client.closeSession(); } } @Override protected void initFile(String id) throws FormatException, IOException { LOGGER.debug("OmeroReader.initFile({})", id); super.initFile(id); if (!id.startsWith("omero:")) { throw new IllegalArgumentException("Not an OMERO id: " + id); } // parse credentials from id string LOGGER.info("Parsing credentials"); String address = server, user = username, pass = password; int port = thePort; long iid = -1; final String[] tokens = id.substring(6).split("\n"); for (String token : tokens) { final int equals = token.indexOf("="); if (equals < 0) continue; final String key = token.substring(0, equals); final String val = token.substring(equals + 1); if (key.equals("server")) address = val; else if (key.equals("user")) user = val; else if (key.equals("pass")) pass = val; else if (key.equals("port")) { try { port = Integer.parseInt(val); } catch (NumberFormatException exc) { } } else if (key.equals("iid")) { try { iid = Long.parseLong(val); } catch (NumberFormatException exc) { } } } if (address == null) { throw new FormatException("Invalid server address"); } if (user == null) { throw new FormatException("Invalid username"); } if (pass == null) { throw new FormatException("Invalid password"); } if (iid < 0) { throw new FormatException("Invalid image ID"); } try { // authenticate with OMERO server LOGGER.info("Logging in"); client = new omero.client(address, port); final ServiceFactoryPrx serviceFactory = client.createSession(user, pass); // get raw pixels store and pixels store = serviceFactory.createRawPixelsStore(); final GatewayPrx gateway = serviceFactory.createGateway(); img = gateway.getImage(iid); long pixelsId = img.getPixels(0).getId().getValue(); store.setPixelsId(pixelsId, false); pix = gateway.getPixels(pixelsId); final int sizeX = pix.getSizeX().getValue(); final int sizeY = pix.getSizeY().getValue(); final int sizeZ = pix.getSizeZ().getValue(); final int sizeC = pix.getSizeC().getValue(); final int sizeT = pix.getSizeT().getValue(); final String pixelType = pix.getPixelsType().getValue().getValue(); // populate metadata LOGGER.info("Populating metadata"); core[0].sizeX = sizeX; core[0].sizeY = sizeY; core[0].sizeZ = sizeZ; core[0].sizeC = sizeC; core[0].sizeT = sizeT; core[0].rgb = false; core[0].littleEndian = false; core[0].dimensionOrder = "XYZCT"; core[0].imageCount = sizeZ * sizeC * sizeT; core[0].pixelType = FormatTools.pixelTypeFromString(pixelType); RDouble x = pix.getPhysicalSizeX(); Double px = x == null ? null : x.getValue(); RDouble y = pix.getPhysicalSizeY(); Double py = y == null ? null : y.getValue(); RDouble z = pix.getPhysicalSizeZ(); Double pz = z == null ? null : z.getValue(); RDouble t = pix.getTimeIncrement(); Double time = t == null ? null : t.getValue(); RString imageName = img.getName(); String name = imageName == null ? null : imageName.getValue(); RString imgDescription = img.getDescription(); String description = imgDescription == null ? null : imgDescription.getValue(); RTime date = img.getAcquisitionDate(); MetadataStore store = getMetadataStore(); MetadataTools.populatePixels(store, this); store.setImageName(name, 0); store.setImageDescription(description, 0); if (date != null) { store.setImageAcquiredDate(DateTools.convertDate(date.getValue(), (int) DateTools.UNIX_EPOCH), 0); } if (px != null && px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0); } if (py != null && py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0); } if (pz != null && pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0); } if (time != null) { store.setPixelsTimeIncrement(time, 0); } List<Channel> channels = pix.copyChannels(); for (int c=0; c<channels.size(); c++) { LogicalChannel channel = channels.get(c).getLogicalChannel(); RInt emWave = channel.getEmissionWave(); RInt exWave = channel.getExcitationWave(); RDouble pinholeSize = channel.getPinHoleSize(); + RString cname = channel.getName(); Integer emission = emWave == null ? null : emWave.getValue(); Integer excitation = exWave == null ? null : exWave.getValue(); - String channelName = channel.getName().getValue(); + String channelName = cname == null ? null : cname.getValue(); Double pinhole = pinholeSize == null ? null : pinholeSize.getValue(); if (channelName != null) { store.setChannelName(channelName, 0, c); } if (pinhole != null) { store.setChannelPinholeSize(pinhole, 0, c); } if (emission != null && emission > 0) { store.setChannelEmissionWavelength( new PositiveInteger(emission), 0, c); } if (excitation != null && excitation > 0) { store.setChannelExcitationWavelength( new PositiveInteger(excitation), 0, c); } } } catch (CannotCreateSessionException e) { throw new FormatException(e); } catch (PermissionDeniedException e) { throw new FormatException(e); } catch (ServerError e) { throw new FormatException(e); } } /** A simple command line tool for downloading images from OMERO. */ public static void main(String[] args) throws Exception { // parse OMERO credentials BufferedReader con = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Server? "); final String server = con.readLine(); System.out.printf("Port [%d]? ", DEFAULT_PORT); final String portString = con.readLine(); final int port = portString.equals("") ? DEFAULT_PORT : Integer.parseInt(portString); System.out.print("Username? "); final String user = con.readLine(); System.out.print("Password? "); final String pass = new String(con.readLine()); System.out.print("Image ID? "); final int imageId = Integer.parseInt(con.readLine()); System.out.print("\n\n"); // construct the OMERO reader final OmeroReader omeroReader = new OmeroReader(); omeroReader.setUsername(user); omeroReader.setPassword(pass); omeroReader.setServer(server); omeroReader.setPort(port); final String id = "omero:iid=" + imageId; try { omeroReader.setId(id); } catch (Exception e) { omeroReader.close(); throw e; } omeroReader.close(); // delegate the heavy lifting to Bio-Formats ImageInfo utility final ImageInfo imageInfo = new ImageInfo(); imageInfo.setReader(omeroReader); // override default image reader String[] readArgs = new String[args.length + 1]; System.arraycopy(args, 0, readArgs, 0, args.length); readArgs[args.length] = id; if (!imageInfo.testRead(readArgs)) { omeroReader.close(); System.exit(1); } } }
false
true
protected void initFile(String id) throws FormatException, IOException { LOGGER.debug("OmeroReader.initFile({})", id); super.initFile(id); if (!id.startsWith("omero:")) { throw new IllegalArgumentException("Not an OMERO id: " + id); } // parse credentials from id string LOGGER.info("Parsing credentials"); String address = server, user = username, pass = password; int port = thePort; long iid = -1; final String[] tokens = id.substring(6).split("\n"); for (String token : tokens) { final int equals = token.indexOf("="); if (equals < 0) continue; final String key = token.substring(0, equals); final String val = token.substring(equals + 1); if (key.equals("server")) address = val; else if (key.equals("user")) user = val; else if (key.equals("pass")) pass = val; else if (key.equals("port")) { try { port = Integer.parseInt(val); } catch (NumberFormatException exc) { } } else if (key.equals("iid")) { try { iid = Long.parseLong(val); } catch (NumberFormatException exc) { } } } if (address == null) { throw new FormatException("Invalid server address"); } if (user == null) { throw new FormatException("Invalid username"); } if (pass == null) { throw new FormatException("Invalid password"); } if (iid < 0) { throw new FormatException("Invalid image ID"); } try { // authenticate with OMERO server LOGGER.info("Logging in"); client = new omero.client(address, port); final ServiceFactoryPrx serviceFactory = client.createSession(user, pass); // get raw pixels store and pixels store = serviceFactory.createRawPixelsStore(); final GatewayPrx gateway = serviceFactory.createGateway(); img = gateway.getImage(iid); long pixelsId = img.getPixels(0).getId().getValue(); store.setPixelsId(pixelsId, false); pix = gateway.getPixels(pixelsId); final int sizeX = pix.getSizeX().getValue(); final int sizeY = pix.getSizeY().getValue(); final int sizeZ = pix.getSizeZ().getValue(); final int sizeC = pix.getSizeC().getValue(); final int sizeT = pix.getSizeT().getValue(); final String pixelType = pix.getPixelsType().getValue().getValue(); // populate metadata LOGGER.info("Populating metadata"); core[0].sizeX = sizeX; core[0].sizeY = sizeY; core[0].sizeZ = sizeZ; core[0].sizeC = sizeC; core[0].sizeT = sizeT; core[0].rgb = false; core[0].littleEndian = false; core[0].dimensionOrder = "XYZCT"; core[0].imageCount = sizeZ * sizeC * sizeT; core[0].pixelType = FormatTools.pixelTypeFromString(pixelType); RDouble x = pix.getPhysicalSizeX(); Double px = x == null ? null : x.getValue(); RDouble y = pix.getPhysicalSizeY(); Double py = y == null ? null : y.getValue(); RDouble z = pix.getPhysicalSizeZ(); Double pz = z == null ? null : z.getValue(); RDouble t = pix.getTimeIncrement(); Double time = t == null ? null : t.getValue(); RString imageName = img.getName(); String name = imageName == null ? null : imageName.getValue(); RString imgDescription = img.getDescription(); String description = imgDescription == null ? null : imgDescription.getValue(); RTime date = img.getAcquisitionDate(); MetadataStore store = getMetadataStore(); MetadataTools.populatePixels(store, this); store.setImageName(name, 0); store.setImageDescription(description, 0); if (date != null) { store.setImageAcquiredDate(DateTools.convertDate(date.getValue(), (int) DateTools.UNIX_EPOCH), 0); } if (px != null && px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0); } if (py != null && py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0); } if (pz != null && pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0); } if (time != null) { store.setPixelsTimeIncrement(time, 0); } List<Channel> channels = pix.copyChannels(); for (int c=0; c<channels.size(); c++) { LogicalChannel channel = channels.get(c).getLogicalChannel(); RInt emWave = channel.getEmissionWave(); RInt exWave = channel.getExcitationWave(); RDouble pinholeSize = channel.getPinHoleSize(); Integer emission = emWave == null ? null : emWave.getValue(); Integer excitation = exWave == null ? null : exWave.getValue(); String channelName = channel.getName().getValue(); Double pinhole = pinholeSize == null ? null : pinholeSize.getValue(); if (channelName != null) { store.setChannelName(channelName, 0, c); } if (pinhole != null) { store.setChannelPinholeSize(pinhole, 0, c); } if (emission != null && emission > 0) { store.setChannelEmissionWavelength( new PositiveInteger(emission), 0, c); } if (excitation != null && excitation > 0) { store.setChannelExcitationWavelength( new PositiveInteger(excitation), 0, c); } } } catch (CannotCreateSessionException e) { throw new FormatException(e); } catch (PermissionDeniedException e) { throw new FormatException(e); } catch (ServerError e) { throw new FormatException(e); } }
protected void initFile(String id) throws FormatException, IOException { LOGGER.debug("OmeroReader.initFile({})", id); super.initFile(id); if (!id.startsWith("omero:")) { throw new IllegalArgumentException("Not an OMERO id: " + id); } // parse credentials from id string LOGGER.info("Parsing credentials"); String address = server, user = username, pass = password; int port = thePort; long iid = -1; final String[] tokens = id.substring(6).split("\n"); for (String token : tokens) { final int equals = token.indexOf("="); if (equals < 0) continue; final String key = token.substring(0, equals); final String val = token.substring(equals + 1); if (key.equals("server")) address = val; else if (key.equals("user")) user = val; else if (key.equals("pass")) pass = val; else if (key.equals("port")) { try { port = Integer.parseInt(val); } catch (NumberFormatException exc) { } } else if (key.equals("iid")) { try { iid = Long.parseLong(val); } catch (NumberFormatException exc) { } } } if (address == null) { throw new FormatException("Invalid server address"); } if (user == null) { throw new FormatException("Invalid username"); } if (pass == null) { throw new FormatException("Invalid password"); } if (iid < 0) { throw new FormatException("Invalid image ID"); } try { // authenticate with OMERO server LOGGER.info("Logging in"); client = new omero.client(address, port); final ServiceFactoryPrx serviceFactory = client.createSession(user, pass); // get raw pixels store and pixels store = serviceFactory.createRawPixelsStore(); final GatewayPrx gateway = serviceFactory.createGateway(); img = gateway.getImage(iid); long pixelsId = img.getPixels(0).getId().getValue(); store.setPixelsId(pixelsId, false); pix = gateway.getPixels(pixelsId); final int sizeX = pix.getSizeX().getValue(); final int sizeY = pix.getSizeY().getValue(); final int sizeZ = pix.getSizeZ().getValue(); final int sizeC = pix.getSizeC().getValue(); final int sizeT = pix.getSizeT().getValue(); final String pixelType = pix.getPixelsType().getValue().getValue(); // populate metadata LOGGER.info("Populating metadata"); core[0].sizeX = sizeX; core[0].sizeY = sizeY; core[0].sizeZ = sizeZ; core[0].sizeC = sizeC; core[0].sizeT = sizeT; core[0].rgb = false; core[0].littleEndian = false; core[0].dimensionOrder = "XYZCT"; core[0].imageCount = sizeZ * sizeC * sizeT; core[0].pixelType = FormatTools.pixelTypeFromString(pixelType); RDouble x = pix.getPhysicalSizeX(); Double px = x == null ? null : x.getValue(); RDouble y = pix.getPhysicalSizeY(); Double py = y == null ? null : y.getValue(); RDouble z = pix.getPhysicalSizeZ(); Double pz = z == null ? null : z.getValue(); RDouble t = pix.getTimeIncrement(); Double time = t == null ? null : t.getValue(); RString imageName = img.getName(); String name = imageName == null ? null : imageName.getValue(); RString imgDescription = img.getDescription(); String description = imgDescription == null ? null : imgDescription.getValue(); RTime date = img.getAcquisitionDate(); MetadataStore store = getMetadataStore(); MetadataTools.populatePixels(store, this); store.setImageName(name, 0); store.setImageDescription(description, 0); if (date != null) { store.setImageAcquiredDate(DateTools.convertDate(date.getValue(), (int) DateTools.UNIX_EPOCH), 0); } if (px != null && px > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(px), 0); } if (py != null && py > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(py), 0); } if (pz != null && pz > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pz), 0); } if (time != null) { store.setPixelsTimeIncrement(time, 0); } List<Channel> channels = pix.copyChannels(); for (int c=0; c<channels.size(); c++) { LogicalChannel channel = channels.get(c).getLogicalChannel(); RInt emWave = channel.getEmissionWave(); RInt exWave = channel.getExcitationWave(); RDouble pinholeSize = channel.getPinHoleSize(); RString cname = channel.getName(); Integer emission = emWave == null ? null : emWave.getValue(); Integer excitation = exWave == null ? null : exWave.getValue(); String channelName = cname == null ? null : cname.getValue(); Double pinhole = pinholeSize == null ? null : pinholeSize.getValue(); if (channelName != null) { store.setChannelName(channelName, 0, c); } if (pinhole != null) { store.setChannelPinholeSize(pinhole, 0, c); } if (emission != null && emission > 0) { store.setChannelEmissionWavelength( new PositiveInteger(emission), 0, c); } if (excitation != null && excitation > 0) { store.setChannelExcitationWavelength( new PositiveInteger(excitation), 0, c); } } } catch (CannotCreateSessionException e) { throw new FormatException(e); } catch (PermissionDeniedException e) { throw new FormatException(e); } catch (ServerError e) { throw new FormatException(e); } }
diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/JobComplete.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/JobComplete.java index fe01bcc226..6f286d8d89 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/JobComplete.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/JobComplete.java @@ -1,67 +1,69 @@ /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jclouds.cloudstack.predicates; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Resource; import javax.inject.Singleton; import org.jclouds.cloudstack.CloudStackClient; import org.jclouds.cloudstack.domain.AsyncJob; import org.jclouds.logging.Logger; import com.google.common.base.Predicate; import com.google.inject.Inject; /** * * Tests to see if a job is in progress. * * @author Adrian Cole */ @Singleton public class JobComplete implements Predicate<Long> { private final CloudStackClient client; @Resource protected Logger logger = Logger.NULL; @Inject public JobComplete(CloudStackClient client) { this.client = client; } public boolean apply(Long jobId) { logger.trace("looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) return false; logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); - if (job.getError() != null) - throw new IllegalStateException(String.format("job %s failed with exception %s", job.getId(), job.getError() + if (job.getError() != null) { + // TODO: create a typed error + throw new RuntimeException(String.format("job %s failed with exception %s", job.getId(), job.getError() .toString())); + } return job.getStatus() > 0; } private AsyncJob<?> refresh(Long jobId) { return client.getAsyncJobClient().getAsyncJob(jobId); } }
false
true
public boolean apply(Long jobId) { logger.trace("looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) return false; logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.getError() != null) throw new IllegalStateException(String.format("job %s failed with exception %s", job.getId(), job.getError() .toString())); return job.getStatus() > 0; }
public boolean apply(Long jobId) { logger.trace("looking for status on job %s", checkNotNull(jobId, "jobId")); AsyncJob<?> job = refresh(jobId); if (job == null) return false; logger.trace("%s: looking for job status %s: currently: %s", job.getId(), 1, job.getStatus()); if (job.getError() != null) { // TODO: create a typed error throw new RuntimeException(String.format("job %s failed with exception %s", job.getId(), job.getError() .toString())); } return job.getStatus() > 0; }
diff --git a/helloworld/src/main/java/org/springframework/amqp/helloworld/BrokerConfigurationApplication.java b/helloworld/src/main/java/org/springframework/amqp/helloworld/BrokerConfigurationApplication.java index b4bb07c..ea51f13 100644 --- a/helloworld/src/main/java/org/springframework/amqp/helloworld/BrokerConfigurationApplication.java +++ b/helloworld/src/main/java/org/springframework/amqp/helloworld/BrokerConfigurationApplication.java @@ -1,22 +1,22 @@ package org.springframework.amqp.helloworld; import org.springframework.amqp.core.AmqpAdmin; import org.springframework.amqp.core.Queue; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BrokerConfigurationApplication { /** * An example application that only configures the AMQP broker */ - public static void main(String[] args) { + public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("rabbitConfiguration.xml"); AmqpAdmin amqpAdmin = context.getBean(AmqpAdmin.class); Queue helloWorldQueue = new Queue("hello.world.queue"); amqpAdmin.declareQueue(helloWorldQueue); } }
true
true
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("rabbitConfiguration.xml"); AmqpAdmin amqpAdmin = context.getBean(AmqpAdmin.class); Queue helloWorldQueue = new Queue("hello.world.queue"); amqpAdmin.declareQueue(helloWorldQueue); }
public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("rabbitConfiguration.xml"); AmqpAdmin amqpAdmin = context.getBean(AmqpAdmin.class); Queue helloWorldQueue = new Queue("hello.world.queue"); amqpAdmin.declareQueue(helloWorldQueue); }
diff --git a/ajax-components/extra/i08/image-browser/src/java/ch/informatica08/yanel/gwt/client/ImageBrowser.java b/ajax-components/extra/i08/image-browser/src/java/ch/informatica08/yanel/gwt/client/ImageBrowser.java index 7f765a5..680943a 100644 --- a/ajax-components/extra/i08/image-browser/src/java/ch/informatica08/yanel/gwt/client/ImageBrowser.java +++ b/ajax-components/extra/i08/image-browser/src/java/ch/informatica08/yanel/gwt/client/ImageBrowser.java @@ -1,111 +1,111 @@ package ch.informatica08.yanel.gwt.client; import org.wyona.yanel.gwt.client.ConfigurableComponentsAware; import org.wyona.yanel.gwt.client.ui.gallery.Gallery; import org.wyona.yanel.gwt.client.ui.gallery.GalleryViewer; import org.wyona.yanel.gwt.client.ui.gallery.ImageItem; import org.wyona.yanel.gwt.client.ui.gallery.Item; import org.wyona.yanel.gwt.client.ui.gallery.TextItem; import ch.informatica08.yanel.gwt.client.ui.gallery.ImageGalleryViewer; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.HTTPRequest; import com.google.gwt.user.client.ResponseTextHandler; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.xml.client.Element; import com.google.gwt.xml.client.NodeList; import com.google.gwt.xml.client.XMLParser; /** * Yanel.ImageBrowser.configurations = {id:&lt;root panel id>, gallery_provider_url : &lt;URL of the data for the component(e.g. atom data)>} * */ public class ImageBrowser extends ConfigurableComponentsAware implements EntryPoint{ public static interface ParameterNames{ public static final String IMAGE_LISTER_URL = "gallery_provider_url"; } public void onModuleLoad() { initializeInstances(); } protected void initializeInstances() { RootPanel [] p = getRootPanels(); for (int i = 0; i < p.length; i++) { if(null == p[i]){ continue; } final int componentNumber = i; Gallery g = new Gallery(){ protected void init() { HTTPRequest.asyncGet(getConfiguration(ParameterNames.IMAGE_LISTER_URL, componentNumber), new ResponseTextHandler(){ public void onCompletion(String responseText) { final Element gallery = XMLParser.parse(responseText).getDocumentElement(); - title = gallery.getElementsByTagName("title").item(0).getFirstChild().toString(); + title = gallery.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();//.toString(); if(title == null){ title = "NO TITLE"; } NodeList nl = gallery.getElementsByTagName("entry"); for (int j = 0; j < nl.getLength(); j++) { Element item = (Element)nl.item(j); - String caption = item.getElementsByTagName("title").item(0).getFirstChild().toString(); + String caption = item.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();//.toString(); String summary = null; String src = ((Element)item.getElementsByTagName("content").item(0)).getAttribute("src"); NodeList summaryNl = item.getElementsByTagName("summary"); if(summaryNl.getLength() > 0){ - summary = ((Element)summaryNl.item(0)).getFirstChild().toString(); + summary = ((Element)summaryNl.item(0)).getFirstChild().getNodeValue();//.toString(); } Item i = new ImageItem(caption, src); i.setSummary(summary); itemCache.put(new Integer(j), i); size++; } if(size <= 0){ itemCache.put(new Integer(0), Item.getNoItemsItem()); size++; } selectItem(0); } }); } protected void retrieveItem(int index) { // Everything is cached during init() } }; GalleryViewer gv = new ImageGalleryViewer(g){ protected Widget getWidgetForItem(Item item) { if (item instanceof ImageItem) { ImageItem imageItem = (ImageItem) item; return new Image(imageItem.getSrc()); }else if (item instanceof TextItem) { TextItem textItem = (TextItem)item; return new Label(textItem.getText()); }else{ return super.getWidgetForItem(item); } } }; p[i].add(gv); } } }
false
true
protected void initializeInstances() { RootPanel [] p = getRootPanels(); for (int i = 0; i < p.length; i++) { if(null == p[i]){ continue; } final int componentNumber = i; Gallery g = new Gallery(){ protected void init() { HTTPRequest.asyncGet(getConfiguration(ParameterNames.IMAGE_LISTER_URL, componentNumber), new ResponseTextHandler(){ public void onCompletion(String responseText) { final Element gallery = XMLParser.parse(responseText).getDocumentElement(); title = gallery.getElementsByTagName("title").item(0).getFirstChild().toString(); if(title == null){ title = "NO TITLE"; } NodeList nl = gallery.getElementsByTagName("entry"); for (int j = 0; j < nl.getLength(); j++) { Element item = (Element)nl.item(j); String caption = item.getElementsByTagName("title").item(0).getFirstChild().toString(); String summary = null; String src = ((Element)item.getElementsByTagName("content").item(0)).getAttribute("src"); NodeList summaryNl = item.getElementsByTagName("summary"); if(summaryNl.getLength() > 0){ summary = ((Element)summaryNl.item(0)).getFirstChild().toString(); } Item i = new ImageItem(caption, src); i.setSummary(summary); itemCache.put(new Integer(j), i); size++; } if(size <= 0){ itemCache.put(new Integer(0), Item.getNoItemsItem()); size++; } selectItem(0); } }); } protected void retrieveItem(int index) { // Everything is cached during init() } }; GalleryViewer gv = new ImageGalleryViewer(g){ protected Widget getWidgetForItem(Item item) { if (item instanceof ImageItem) { ImageItem imageItem = (ImageItem) item; return new Image(imageItem.getSrc()); }else if (item instanceof TextItem) { TextItem textItem = (TextItem)item; return new Label(textItem.getText()); }else{ return super.getWidgetForItem(item); } } }; p[i].add(gv); } }
protected void initializeInstances() { RootPanel [] p = getRootPanels(); for (int i = 0; i < p.length; i++) { if(null == p[i]){ continue; } final int componentNumber = i; Gallery g = new Gallery(){ protected void init() { HTTPRequest.asyncGet(getConfiguration(ParameterNames.IMAGE_LISTER_URL, componentNumber), new ResponseTextHandler(){ public void onCompletion(String responseText) { final Element gallery = XMLParser.parse(responseText).getDocumentElement(); title = gallery.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();//.toString(); if(title == null){ title = "NO TITLE"; } NodeList nl = gallery.getElementsByTagName("entry"); for (int j = 0; j < nl.getLength(); j++) { Element item = (Element)nl.item(j); String caption = item.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();//.toString(); String summary = null; String src = ((Element)item.getElementsByTagName("content").item(0)).getAttribute("src"); NodeList summaryNl = item.getElementsByTagName("summary"); if(summaryNl.getLength() > 0){ summary = ((Element)summaryNl.item(0)).getFirstChild().getNodeValue();//.toString(); } Item i = new ImageItem(caption, src); i.setSummary(summary); itemCache.put(new Integer(j), i); size++; } if(size <= 0){ itemCache.put(new Integer(0), Item.getNoItemsItem()); size++; } selectItem(0); } }); } protected void retrieveItem(int index) { // Everything is cached during init() } }; GalleryViewer gv = new ImageGalleryViewer(g){ protected Widget getWidgetForItem(Item item) { if (item instanceof ImageItem) { ImageItem imageItem = (ImageItem) item; return new Image(imageItem.getSrc()); }else if (item instanceof TextItem) { TextItem textItem = (TextItem)item; return new Label(textItem.getText()); }else{ return super.getWidgetForItem(item); } } }; p[i].add(gv); } }
diff --git a/me/boecki/SignCodePad/event/SignCreate.java b/me/boecki/SignCodePad/event/SignCreate.java index 5b8d65d..e179874 100644 --- a/me/boecki/SignCodePad/event/SignCreate.java +++ b/me/boecki/SignCodePad/event/SignCreate.java @@ -1,327 +1,328 @@ package me.boecki.SignCodePad.event; import me.boecki.SignCodePad.MD5; import me.boecki.SignCodePad.SignCodePad; import me.boecki.SignCodePad.SignLoc; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockListener; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.inventory.ItemStack; public class SignCreate extends BlockListener { SignCodePad plugin; public SignCreate(SignCodePad pplugin) { plugin = pplugin; } public void onBlockBreak(BlockBreakEvent event) { if (event.getBlock().getTypeId() == Material.WALL_SIGN.getId()) { if (plugin.hasSetting(event.getBlock().getLocation())) { if(plugin.getSetting(event.getBlock().getLocation(), "Owner") == event.getPlayer() || plugin.hasPermission(event.getPlayer(), "SignCodePad.masterdestroy")){ plugin.removeSetting(event.getBlock().getLocation()); event.getPlayer().sendMessage("CodePad Destroyed."); plugin.save(); } else { event.getPlayer().sendMessage("You do not own this SignCodePad."); event.setCancelled(true); } } } } private Block getBlockBehind(Sign sign) { Location signloc = sign.getBlock().getLocation(); double x = -1; double y = signloc.getY(); double z = -1; switch ((int) sign.getRawData()) { //Westen case 2: x = signloc.getX(); z = signloc.getZ() + 2; break; //Osten case 3: x = signloc.getX(); z = signloc.getZ() - 2; break; //S�den case 4: x = signloc.getX() + 2; z = signloc.getZ(); break; //Norden case 5: x = signloc.getX() - 2; z = signloc.getZ(); break; } return sign.getBlock().getWorld() .getBlockAt(new Location(sign.getBlock().getWorld(), x, y, z)); } public void onSignChange(SignChangeEvent event) { - if (event.getLine(0).equalsIgnoreCase("[SignCodePad]")) { + if (event.getBlock().getTypeId() != Material.WALL_SIGN.getId()) return; + if (event.getLine(0).equalsIgnoreCase("[SignCodePad]") || event.getLine(0).equalsIgnoreCase("[SCP]")) { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.use")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } if (event.getLine(1).equalsIgnoreCase("Cal")) { plugin.CalLoc.put(event.getPlayer().getName(), new SignLoc(event.getBlock().getLocation())); plugin.CalSaverList.put(event.getPlayer().getName(), new CalSaver()); event.setLine(0, "+ "); event.setLine(1, "Press the"); event.setLine(2, "cross"); event.setLine(3, ""); } else { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.create")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } boolean Worked = true; int Number = 0; try { Number = Integer.parseInt(event.getLine(1)); } catch (Exception e) { Worked = false; } if (Worked) { if ((Number < 10000) && (Number > 999)) { MD5 md5 = new MD5(Number); if (md5.isGen()) { if (!Zeiledrei(event.getLine(2), event) || !Zeilevier(event.getLine(3), event)) { return; } plugin.setSetting(event.getBlock().getLocation(), "MD5", md5.getValue()); plugin.setSetting(event.getBlock().getLocation(), "Owner", event.getPlayer().getName()); event.setLine(0, "1 2 3 | "); event.setLine(1, "4 5 6 | ----"); event.setLine(2, "7 8 9 | <<- "); event.setLine(3, "* 0 # | OK "); Block block = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "OK-Location")); if(block.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("OK-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } block.setTypeId(Material.TORCH.getId()); if (((Location) plugin.getSetting(event.getBlock().getLocation(),"Error-Location")).getY() >= 0) { Block blockb = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "Error-Location")); if(blockb.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("Error-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } blockb.setTypeId(Material.TORCH.getId()); } plugin.save(); event.getPlayer().sendMessage("CodePad Created."); } else { event.getPlayer() .sendMessage("Internal Error (MD5)."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } } } private boolean Zeiledrei(String line, SignChangeEvent event) { String[] linesplit = line.split(";"); if (linesplit[0] != "" && linesplit[0].length()>0) { plugin.setSetting(event.getBlock().getLocation(), "OK-Delay", linesplit[0]); } else { plugin.setSetting(event.getBlock().getLocation(), "OK-Delay", 3); } if ((linesplit.length > 1) && (linesplit[1] != "")) { String[] loc = linesplit[1].split(","); if (loc.length < 3) { event.getPlayer() .sendMessage("Error in Line 3. (Destination Format) ("+loc.length+")"); return false; } if ((loc[0] == "") || (loc[1] == "") || (loc[2] == "")) { event.getPlayer() .sendMessage("Error in Line 3. (Destination Format)"); return false; } Location blockloc = getBlockBehind((Sign) event.getBlock().getState()) .getLocation(); double x = blockloc.getX(); double y = blockloc.getY() + Integer.parseInt(loc[1]); double z = blockloc.getZ(); switch ((int) ((Sign) event.getBlock().getState()).getRawData()) { //Westen case 2: x += (Integer.parseInt(loc[2]) * -1); z += Integer.parseInt(loc[0]); break; //Osten case 3: x += Integer.parseInt(loc[2]); z += (Integer.parseInt(loc[0]) * -1); break; //S�den case 4: x += Integer.parseInt(loc[0]); z += Integer.parseInt(loc[2]); break; //Norden case 5: x += (Integer.parseInt(loc[0]) * -1); z += (Integer.parseInt(loc[2]) * -1); break; } plugin.setSetting(event.getBlock().getLocation(), "OK-Location", new Location(event.getBlock().getWorld(), x, y, z)); } else { plugin.setSetting(event.getBlock().getLocation(), "OK-Location", getBlockBehind((Sign) event.getBlock().getState()).getLocation()); } return true; } private boolean Zeilevier(String line, SignChangeEvent event) { String[] linesplit = line.split(";"); if (linesplit[0] != "" && linesplit[0].length()>0) { plugin.setSetting(event.getBlock().getLocation(), "Error-Delay", linesplit[0]); } else { plugin.setSetting(event.getBlock().getLocation(), "Error-Delay", 3); } if ((linesplit.length > 1) && (linesplit[1] != "")) { String[] loc = linesplit[1].split(","); if (loc.length < 3) { event.getPlayer() .sendMessage("Error in Line 4. (Destination Format) ("+loc.length+")"); return false; } if ((loc[0] == "") || (loc[1] == "") || (loc[2] == "")) { event.getPlayer() .sendMessage("Error in Line 4. (Destination Format)"); return false; } Location blockloc = getBlockBehind((Sign) event.getBlock().getState()) .getLocation(); double x = blockloc.getX(); double y = blockloc.getY() + Integer.parseInt(loc[1]); double z = blockloc.getZ(); switch ((int) ((Sign) event.getBlock().getState()).getRawData()) { //Westen case 2: x += (Integer.parseInt(loc[2]) * -1); z += Integer.parseInt(loc[0]); break; //Osten case 3: x += Integer.parseInt(loc[2]); z += (Integer.parseInt(loc[0]) * -1); break; //S�den case 4: x += Integer.parseInt(loc[0]); z += Integer.parseInt(loc[2]); break; //Norden case 5: x += (Integer.parseInt(loc[0]) * -1); z += (Integer.parseInt(loc[2]) * -1); break; } plugin.setSetting(event.getBlock().getLocation(), "Error-Location", new Location(event.getBlock().getWorld(), x, y, z)); } else { plugin.setSetting(event.getBlock().getLocation(), "Error-Location", new Location(event.getBlock().getWorld(), 0, -1, 0)); } if ((linesplit.length > 2) && (linesplit[2] != "")) { String sCount = linesplit[2]; int Count = Integer.parseInt(sCount); plugin.setSetting(event.getBlock().getLocation(), "Error-Count", Count); } else { plugin.setSetting(event.getBlock().getLocation(), "Error-Count", 0); } return true; } }
true
true
public void onSignChange(SignChangeEvent event) { if (event.getLine(0).equalsIgnoreCase("[SignCodePad]")) { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.use")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } if (event.getLine(1).equalsIgnoreCase("Cal")) { plugin.CalLoc.put(event.getPlayer().getName(), new SignLoc(event.getBlock().getLocation())); plugin.CalSaverList.put(event.getPlayer().getName(), new CalSaver()); event.setLine(0, "+ "); event.setLine(1, "Press the"); event.setLine(2, "cross"); event.setLine(3, ""); } else { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.create")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } boolean Worked = true; int Number = 0; try { Number = Integer.parseInt(event.getLine(1)); } catch (Exception e) { Worked = false; } if (Worked) { if ((Number < 10000) && (Number > 999)) { MD5 md5 = new MD5(Number); if (md5.isGen()) { if (!Zeiledrei(event.getLine(2), event) || !Zeilevier(event.getLine(3), event)) { return; } plugin.setSetting(event.getBlock().getLocation(), "MD5", md5.getValue()); plugin.setSetting(event.getBlock().getLocation(), "Owner", event.getPlayer().getName()); event.setLine(0, "1 2 3 | "); event.setLine(1, "4 5 6 | ----"); event.setLine(2, "7 8 9 | <<- "); event.setLine(3, "* 0 # | OK "); Block block = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "OK-Location")); if(block.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("OK-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } block.setTypeId(Material.TORCH.getId()); if (((Location) plugin.getSetting(event.getBlock().getLocation(),"Error-Location")).getY() >= 0) { Block blockb = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "Error-Location")); if(blockb.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("Error-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } blockb.setTypeId(Material.TORCH.getId()); } plugin.save(); event.getPlayer().sendMessage("CodePad Created."); } else { event.getPlayer() .sendMessage("Internal Error (MD5)."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } } }
public void onSignChange(SignChangeEvent event) { if (event.getBlock().getTypeId() != Material.WALL_SIGN.getId()) return; if (event.getLine(0).equalsIgnoreCase("[SignCodePad]") || event.getLine(0).equalsIgnoreCase("[SCP]")) { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.use")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } if (event.getLine(1).equalsIgnoreCase("Cal")) { plugin.CalLoc.put(event.getPlayer().getName(), new SignLoc(event.getBlock().getLocation())); plugin.CalSaverList.put(event.getPlayer().getName(), new CalSaver()); event.setLine(0, "+ "); event.setLine(1, "Press the"); event.setLine(2, "cross"); event.setLine(3, ""); } else { if(!plugin.hasPermission(event.getPlayer(), "SignCodePad.create")){ event.getPlayer().sendMessage("You do not have Permission to do that."); event.getBlock().setType(Material.AIR); event.getBlock().getLocation().getWorld() .dropItem(event.getBlock().getLocation(), new ItemStack(Material.SIGN, 1)); return; } boolean Worked = true; int Number = 0; try { Number = Integer.parseInt(event.getLine(1)); } catch (Exception e) { Worked = false; } if (Worked) { if ((Number < 10000) && (Number > 999)) { MD5 md5 = new MD5(Number); if (md5.isGen()) { if (!Zeiledrei(event.getLine(2), event) || !Zeilevier(event.getLine(3), event)) { return; } plugin.setSetting(event.getBlock().getLocation(), "MD5", md5.getValue()); plugin.setSetting(event.getBlock().getLocation(), "Owner", event.getPlayer().getName()); event.setLine(0, "1 2 3 | "); event.setLine(1, "4 5 6 | ----"); event.setLine(2, "7 8 9 | <<- "); event.setLine(3, "* 0 # | OK "); Block block = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "OK-Location")); if(block.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("OK-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } block.setTypeId(Material.TORCH.getId()); if (((Location) plugin.getSetting(event.getBlock().getLocation(),"Error-Location")).getY() >= 0) { Block blockb = event.getPlayer().getWorld().getBlockAt((Location) plugin.getSetting(event.getBlock().getLocation(), "Error-Location")); if(blockb.getType() != Material.AIR&&!plugin.hasPermission(event.getPlayer(),"SignCodePad.replaceblock")){ event.getPlayer().sendMessage("Error-Target not Air."); if (plugin.hasSetting(event.getBlock().getLocation())) { plugin.removeSetting(event.getBlock().getLocation()); plugin.save(); } return; } blockb.setTypeId(Material.TORCH.getId()); } plugin.save(); event.getPlayer().sendMessage("CodePad Created."); } else { event.getPlayer() .sendMessage("Internal Error (MD5)."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } else { event.getPlayer().sendMessage("Wrong Code."); } } } }
diff --git a/jmock/extensions/cglib/acceptance-tests/atest/jmock/cglib/MockConcreteClassAcceptanceTest.java b/jmock/extensions/cglib/acceptance-tests/atest/jmock/cglib/MockConcreteClassAcceptanceTest.java index 1954e0ef..7fac78d3 100644 --- a/jmock/extensions/cglib/acceptance-tests/atest/jmock/cglib/MockConcreteClassAcceptanceTest.java +++ b/jmock/extensions/cglib/acceptance-tests/atest/jmock/cglib/MockConcreteClassAcceptanceTest.java @@ -1,26 +1,26 @@ /** * @author Aslak Helles&oslash;y * @version $Revision$ */ package atest.jmock.cglib; import java.util.ArrayList; import org.jmock.cglib.Mock; import org.jmock.cglib.MockObjectTestCase; public class MockConcreteClassAcceptanceTest extends MockObjectTestCase { public void testCanMockConcreteClasses() throws Exception { Mock listMock = new Mock(ArrayList.class,"listMock"); assertTrue( "proxy is an ArrayList", listMock.proxy() instanceof ArrayList ); ArrayList proxy = (ArrayList)listMock.proxy(); Object newElement = newDummy("newElement"); - listMock.expect(once()).method("add").with(eq(newElement)).will(returnValue(true)); + listMock.expects(once()).method("add").with(eq(newElement)).will(returnValue(true)); proxy.add(newElement); listMock.verify(); } }
true
true
public void testCanMockConcreteClasses() throws Exception { Mock listMock = new Mock(ArrayList.class,"listMock"); assertTrue( "proxy is an ArrayList", listMock.proxy() instanceof ArrayList ); ArrayList proxy = (ArrayList)listMock.proxy(); Object newElement = newDummy("newElement"); listMock.expect(once()).method("add").with(eq(newElement)).will(returnValue(true)); proxy.add(newElement); listMock.verify(); }
public void testCanMockConcreteClasses() throws Exception { Mock listMock = new Mock(ArrayList.class,"listMock"); assertTrue( "proxy is an ArrayList", listMock.proxy() instanceof ArrayList ); ArrayList proxy = (ArrayList)listMock.proxy(); Object newElement = newDummy("newElement"); listMock.expects(once()).method("add").with(eq(newElement)).will(returnValue(true)); proxy.add(newElement); listMock.verify(); }
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java index 00b17549..6560c5d3 100644 --- a/src/com/android/launcher2/LauncherModel.java +++ b/src/com/android/launcher2/LauncherModel.java @@ -1,1397 +1,1397 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher2; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Parcelable; import android.os.RemoteException; import android.util.Log; import android.os.Process; import android.os.SystemClock; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.android.launcher.R; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private final LauncherApplication mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private Loader mLoader = new Loader(); private boolean mBeforeFirstLoad = true; private WeakReference<Callbacks> mCallbacks; private AllAppsList mAllAppsList; private IconCache mIconCache; private Bitmap mDefaultIcon; public interface Callbacks { public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsAdded(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindAppsRemoved(ArrayList<ApplicationInfo> apps); } LauncherModel(LauncherApplication app, IconCache iconCache) { mApp = app; mAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( app.getPackageManager().getDefaultActivityIcon(), app); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screen, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screen, cellX, cellY); } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screen); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final PackageManager packageManager = mContext.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); } Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR); Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR); if (DEBUG_LOADERS) { Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone(); // We're adding this now, so clear out this so we don't re-send them. mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } if (DEBUG_LOADERS) { Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis() - t) + "ms"); } } }); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { - return getShortcutInfo(manager, intent, context); + return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } info.setIcon(icon); break; default: info.setIcon(getFallbackIcon()); info.usingFallbackIcon = true; info.customIcon = false; break; } return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
true
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final PackageManager packageManager = mContext.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); } Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR); Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR); if (DEBUG_LOADERS) { Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone(); // We're adding this now, so clear out this so we don't re-send them. mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } if (DEBUG_LOADERS) { Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis() - t) + "ms"); } } }); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } info.setIcon(icon); break; default: info.setIcon(getFallbackIcon()); info.usingFallbackIcon = true; info.customIcon = false; break; } return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: folderInfo = findOrMakeUserFolder(folderList, id); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: folderInfo = findOrMakeLiveFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, ItemInfo item, long container, int screen, int cellX, int cellY, boolean notify) { item.container = container; item.screen = screen; item.cellX = cellX; item.cellY = cellY; final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); if (result != null) { item.id = Integer.parseInt(result.getPathSegments().get(1)); } } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, ItemInfo item) { final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, ItemInfo item) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null); } /** * Remove the contents of the specified folder from the database */ static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) { final ContentResolver cr = context.getContentResolver(); cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); cr.delete(LauncherSettings.Favorites.CONTENT_URI, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } public void startLoader(Context context, boolean isLaunching) { mLoader.startLoader(context, isLaunching); } public void stopLoader() { mLoader.stopLoader(); } /** * We pick up most of the changes to all apps. */ public void setAllAppsDirty() { mLoader.setAllAppsDirty(); } public void setWorkspaceDirty() { mLoader.setWorkspaceDirty(); } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ public void onReceive(Context context, Intent intent) { // Use the app as the context. context = mApp; ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> removed = null; ArrayList<ApplicationInfo> modified = null; synchronized (mLock) { if (mBeforeFirstLoad) { // If we haven't even loaded yet, don't bother, since we'll just pick // up the changes. return; } final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { mAllAppsList.updatePackage(context, packageName); } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { mAllAppsList.removePackage(packageName); } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { mAllAppsList.addPackage(context, packageName); } else { mAllAppsList.updatePackage(context, packageName); } } if (mAllAppsList.added.size() > 0) { added = mAllAppsList.added; mAllAppsList.added = new ArrayList<ApplicationInfo>(); } if (mAllAppsList.removed.size() > 0) { removed = mAllAppsList.removed; mAllAppsList.removed = new ArrayList<ApplicationInfo>(); for (ApplicationInfo info: removed) { mIconCache.remove(info.intent.getComponent()); } } if (mAllAppsList.modified.size() > 0) { modified = mAllAppsList.modified; mAllAppsList.modified = new ArrayList<ApplicationInfo>(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { final ArrayList<ApplicationInfo> addedFinal = added; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsAdded(addedFinal); } }); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsUpdated(modifiedFinal); } }); } if (removed != null) { final ArrayList<ApplicationInfo> removedFinal = removed; mHandler.post(new Runnable() { public void run() { callbacks.bindAppsRemoved(removedFinal); } }); } } else { if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String packages[] = intent.getStringArrayExtra( Intent.EXTRA_CHANGED_PACKAGE_LIST); if (packages == null || packages.length == 0) { return; } setAllAppsDirty(); setWorkspaceDirty(); startLoader(context, false); } } } } public class Loader { private static final int ITEMS_CHUNK = 6; private LoaderThread mLoaderThread; private int mLastWorkspaceSeq = 0; private int mWorkspaceSeq = 1; private int mLastAllAppsSeq = 0; private int mAllAppsSeq = 1; final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>(); final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); /** * Call this from the ui thread so the handler is initialized on the correct thread. */ public Loader() { } public void startLoader(Context context, boolean isLaunching) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks.get() != null) { LoaderThread oldThread = mLoaderThread; if (oldThread != null) { if (oldThread.isLaunching()) { // don't downgrade isLaunching if we're already running isLaunching = true; } oldThread.stopLocked(); } mLoaderThread = new LoaderThread(context, oldThread, isLaunching); mLoaderThread.start(); } } } public void stopLoader() { synchronized (mLock) { if (mLoaderThread != null) { mLoaderThread.stopLocked(); } } } public void setWorkspaceDirty() { synchronized (mLock) { mWorkspaceSeq++; } } public void setAllAppsDirty() { synchronized (mLock) { mAllAppsSeq++; } } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderThread extends Thread { private Context mContext; private Thread mWaitThread; private boolean mIsLaunching; private boolean mStopped; private boolean mWorkspaceDoneBinding; LoaderThread(Context context, Thread waitThread, boolean isLaunching) { mContext = context; mWaitThread = waitThread; mIsLaunching = isLaunching; } boolean isLaunching() { return mIsLaunching; } /** * If another LoaderThread was supplied, we need to wait for that to finish before * we start our processing. This keeps the ordering of the setting and clearing * of the dirty flags correct by making sure we don't start processing stuff until * they've had a chance to re-set them. We do this waiting the worker thread, not * the ui thread to avoid ANRs. */ private void waitForOtherThread() { if (mWaitThread != null) { boolean done = false; while (!done) { try { mWaitThread.join(); done = true; } catch (InterruptedException ex) { // Ignore } } mWaitThread = null; } } public void run() { waitForOtherThread(); // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } // Load the workspace only if it's dirty. int workspaceSeq; boolean workspaceDirty; synchronized (mLock) { workspaceSeq = mWorkspaceSeq; workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq; } if (workspaceDirty) { loadWorkspace(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mWorkspaceSeq. if (mStopped) { return; } if (workspaceSeq == mWorkspaceSeq) { mLastWorkspaceSeq = mWorkspaceSeq; } } // Bind the workspace bindWorkspace(); // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderThread.this) { mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderThread.this) { mWorkspaceDoneBinding = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with workspace"); } LoaderThread.this.notify(); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "waiting to be done with workspace"); } while (!mStopped && !mWorkspaceDoneBinding) { try { this.wait(); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "done waiting to be done with workspace"); } } // Load all apps if they're dirty int allAppsSeq; boolean allAppsDirty; synchronized (mLock) { allAppsSeq = mAllAppsSeq; allAppsDirty = mAllAppsSeq != mLastAllAppsSeq; if (DEBUG_LOADERS) { Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty"); } } if (allAppsDirty) { loadAllApps(); } synchronized (mLock) { // If we're not stopped, and nobody has incremented mAllAppsSeq. if (mStopped) { return; } if (allAppsSeq == mAllAppsSeq) { mLastAllAppsSeq = mAllAppsSeq; } } // Bind all apps if (allAppsDirty) { bindAllApps(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // Setting the reference is atomic, but we can't do it inside the other critical // sections. mLoaderThread = null; } } public void stopLocked() { synchronized (LoaderThread.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. */ Callbacks tryGetCallbacks() { synchronized (mLock) { if (mStopped) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void loadWorkspace() { long t = SystemClock.uptimeMillis(); final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); mItems.clear(); mAppWidgets.clear(); mFolders.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Cursor c = contentResolver.query( LauncherSettings.Favorites.CONTENT_URI, null, null, null, null); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); final int displayModeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); } if (info != null) { updateSavedIcon(context, info, c, iconIndex); info.intent = intent; info.id = c.getLong(idIndex); container = c.getInt(containerIndex); info.container = container; info.screen = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(info); break; default: // Item is in a user folder UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, container); folderInfo.add(info); break; } } else { // Failed to load the shortcut, probably because the // activity manager couldn't resolve it (maybe the app // was uninstalled), or the db row was somehow screwed up. // Delete it. id = c.getLong(idIndex); Log.e(TAG, "Error loading shortcut " + id + ", removing it"); contentResolver.delete(LauncherSettings.Favorites.getContentUri( id, false), null, null); } break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: id = c.getLong(idIndex); UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screen = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(folderInfo); break; } mFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: id = c.getLong(idIndex); Uri uri = Uri.parse(c.getString(uriIndex)); // Make sure the live folder exists final ProviderInfo providerInfo = context.getPackageManager().resolveContentProvider( uri.getAuthority(), 0); if (providerInfo == null && !isSafeMode) { itemsToRemove.add(id); } else { LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id); intentDescription = c.getString(intentIndex); intent = null; if (intentDescription != null) { try { intent = Intent.parseUri(intentDescription, 0); } catch (URISyntaxException e) { // Ignore, a live folder might not have a base intent } } liveFolderInfo.title = c.getString(titleIndex); liveFolderInfo.id = id; liveFolderInfo.uri = uri; container = c.getInt(containerIndex); liveFolderInfo.container = container; liveFolderInfo.screen = c.getInt(screenIndex); liveFolderInfo.cellX = c.getInt(cellXIndex); liveFolderInfo.cellY = c.getInt(cellYIndex); liveFolderInfo.baseIntent = intent; liveFolderInfo.displayMode = c.getInt(displayModeIndex); loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex, iconResourceIndex, liveFolderInfo); switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: mItems.add(liveFolderInfo); break; } mFolders.put(liveFolderInfo.id, liveFolderInfo); } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId); appWidgetInfo.id = id; appWidgetInfo.screen = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { Log.e(TAG, "Widget found where container " + "!= CONTAINER_DESKTOP -- ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); mAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { c.close(); } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } } /** * Read everything out of our database. */ private void bindWorkspace() { final long t = SystemClock.uptimeMillis(); // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. Callbacks callbacks = mCallbacks.get(); if (callbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderThread running with no launcher"); return; } int N; // Tell the workspace that we're about to start firing items at it mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.startBinding(); } } }); // Add the items to the workspace. N = mItems.size(); for (int i=0; i<N; i+=ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindItems(mItems, start, start+chunkSize); } } }); } mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindFolders(mFolders); } } }); // Wait until the queue goes empty. mHandler.postIdle(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "Going to start binding widgets soon."); } } }); // Bind the widgets, one at a time. // WARNING: this is calling into the workspace from the background thread, // but since getCurrentScreen() just returns the int, we should be okay. This // is just a hint for the order, and if it's wrong, we'll be okay. // TODO: instead, we should have that push the current screen into here. final int currentScreen = callbacks.getCurrentWorkspaceScreen(); N = mAppWidgets.size(); // once for the current screen for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen == currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // once for the other screens for (int i=0; i<N; i++) { final LauncherAppWidgetInfo widget = mAppWidgets.get(i); if (widget.screen != currentScreen) { mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }); } } // Tell the workspace that we're done. mHandler.post(new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.finishBindingItems(); } } }); // If we're profiling, this is the last thing in the queue. mHandler.post(new Runnable() { public void run() { if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } if (Launcher.PROFILE_ROTATE) { android.os.Debug.stopMethodTracing(); } } }); } private void loadAllApps() { final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final Callbacks callbacks = tryGetCallbacks(); if (callbacks == null) { return; } final PackageManager packageManager = mContext.getPackageManager(); final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); synchronized (mLock) { mBeforeFirstLoad = false; mAllAppsList.clear(); if (apps != null) { long t = SystemClock.uptimeMillis(); int N = apps.size(); for (int i=0; i<N && !mStopped; i++) { // This builds the icon bitmaps. mAllAppsList.add(new ApplicationInfo(apps.get(i), mIconCache)); } Collections.sort(mAllAppsList.data, APP_NAME_COMPARATOR); Collections.sort(mAllAppsList.added, APP_NAME_COMPARATOR); if (DEBUG_LOADERS) { Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms"); } } } } private void bindAllApps() { synchronized (mLock) { final ArrayList<ApplicationInfo> results = (ArrayList<ApplicationInfo>) mAllAppsList.data.clone(); // We're adding this now, so clear out this so we don't re-send them. mAllAppsList.added = new ArrayList<ApplicationInfo>(); mHandler.post(new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final int count = results.size(); Callbacks callbacks = tryGetCallbacks(); if (callbacks != null) { callbacks.bindAllApplications(results); } if (DEBUG_LOADERS) { Log.d(TAG, "bound app " + count + " icons in " + (SystemClock.uptimeMillis() - t) + "ms"); } } }); } } public void dumpState() { Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext); Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread); Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped); Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding); } } public void dumpState() { Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq); Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq); Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq); Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq); Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size()); if (mLoaderThread != null) { mLoaderThread.dumpState(); } else { Log.d(TAG, "mLoader.mLoaderThread=null"); } } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); ComponentName componentName = intent.getComponent(); if (componentName == null) { return null; } // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0); if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { info.title = resolveInfo.activityInfo.loadLabel(manager); } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } info.setIcon(icon); break; default: info.setIcon(getFallbackIcon()); info.usingFallbackIcon = true; info.customIcon = false; break; } return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex) { if (false) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return BitmapFactory.decodeByteArray(data, 0, data.length); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data); addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private ShortcutInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Bitmap icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) { int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); try { Resources resources = packageManager.getResourcesForApplication(packageName); final int id = resources.getIdentifier(resourceName, null, null); liveFolderInfo.icon = Utilities.createIconBitmap(resources.getDrawable(id), context); } catch (Exception e) { liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } liveFolderInfo.iconResource = new Intent.ShortcutIconResource(); liveFolderInfo.iconResource.packageName = packageName; liveFolderInfo.iconResource.resourceName = resourceName; break; default: liveFolderInfo.icon = Utilities.createIconBitmap( context.getResources().getDrawable(R.drawable.ic_launcher_folder), context); } } void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) { // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (info.onExternalStorage && !info.customIcon && !info.usingFallbackIcon) { boolean needSave; byte[] data = c.getBlob(iconIndex); try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens either // after the froyo OTA or when the app is updated with a new // icon. updateItemInDatabase(context, info); } } } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, * or make a new one. */ private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) { // No placeholder -- create a new instance folderInfo = new UserFolderInfo(); folders.put(id, folderInfo); } return (UserFolderInfo) folderInfo; } /** * Return an existing UserFolderInfo object if we have encountered this ID previously, or make a * new one. */ private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) { // No placeholder -- create a new instance folderInfo = new LiveFolderInfo(); folders.put(id, folderInfo); } return (LiveFolderInfo) folderInfo; } private static String getLabel(PackageManager manager, ActivityInfo activityInfo) { String label = activityInfo.loadLabel(manager).toString(); if (label == null) { label = manager.getApplicationLabel(activityInfo.applicationInfo).toString(); if (label == null) { label = activityInfo.name; } } return label; } private static final Collator sCollator = Collator.getInstance(); public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { return sCollator.compare(a.title.toString(), b.title.toString()); } }; public void dumpState() { Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad); Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified); mLoader.dumpState(); } }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISAdminMenuInventory.java b/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISAdminMenuInventory.java index 7b9429a2b..52225cea7 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISAdminMenuInventory.java +++ b/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISAdminMenuInventory.java @@ -1,81 +1,81 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.commands.admin; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeSet; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; /** * The Administrator of Solos is the Earth Empire's civilian overseer for that * planet. * * @author eccentric_nz */ public class TARDISAdminMenuInventory { private final TARDIS plugin; private final ItemStack[] menu; public TARDISAdminMenuInventory(TARDIS plugin) { this.plugin = plugin; this.menu = getItemStack(); } /** * Constructs an inventory for the Admin Menu GUI. * * @return an Array of itemStacks (an inventory) */ @SuppressWarnings("deprecation") private ItemStack[] getItemStack() { List<ItemStack> options = new ArrayList<ItemStack>(); int i = 0; Set<String> config = new TreeSet(plugin.getConfig().getKeys(true)); for (String c : config) { String value = plugin.getConfig().getString(c); - if ((value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) && !c.equals("conversion_done") && !c.equals("location_conversion_done")) { + if ((value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) && !c.startsWith("conversions") && !c.startsWith("worlds")) { ItemStack is = new ItemStack(TARDISConstants.GUI_ITEMS.get(i), 1); ItemMeta im = is.getItemMeta(); im.setDisplayName(c); im.setLore(Arrays.asList(new String[]{value})); is.setItemMeta(im); options.add(is); i++; } } ItemStack[] stack = new ItemStack[54]; for (int s = 0; s < 54; s++) { if (s < options.size()) { stack[s] = options.get(s); } else { stack[s] = null; } } return stack; } public ItemStack[] getMenu() { return menu; } }
true
true
private ItemStack[] getItemStack() { List<ItemStack> options = new ArrayList<ItemStack>(); int i = 0; Set<String> config = new TreeSet(plugin.getConfig().getKeys(true)); for (String c : config) { String value = plugin.getConfig().getString(c); if ((value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) && !c.equals("conversion_done") && !c.equals("location_conversion_done")) { ItemStack is = new ItemStack(TARDISConstants.GUI_ITEMS.get(i), 1); ItemMeta im = is.getItemMeta(); im.setDisplayName(c); im.setLore(Arrays.asList(new String[]{value})); is.setItemMeta(im); options.add(is); i++; } } ItemStack[] stack = new ItemStack[54]; for (int s = 0; s < 54; s++) { if (s < options.size()) { stack[s] = options.get(s); } else { stack[s] = null; } } return stack; }
private ItemStack[] getItemStack() { List<ItemStack> options = new ArrayList<ItemStack>(); int i = 0; Set<String> config = new TreeSet(plugin.getConfig().getKeys(true)); for (String c : config) { String value = plugin.getConfig().getString(c); if ((value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) && !c.startsWith("conversions") && !c.startsWith("worlds")) { ItemStack is = new ItemStack(TARDISConstants.GUI_ITEMS.get(i), 1); ItemMeta im = is.getItemMeta(); im.setDisplayName(c); im.setLore(Arrays.asList(new String[]{value})); is.setItemMeta(im); options.add(is); i++; } } ItemStack[] stack = new ItemStack[54]; for (int s = 0; s < 54; s++) { if (s < options.size()) { stack[s] = options.get(s); } else { stack[s] = null; } } return stack; }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfaceEditor.java b/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfaceEditor.java index 94788050..7452632d 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfaceEditor.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/general/InterfaceEditor.java @@ -1,284 +1,285 @@ package org.jboss.as.console.client.shared.general; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.ProvidesKey; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.shared.general.model.Interface; import org.jboss.as.console.client.shared.general.validation.ValidationResult; import org.jboss.as.console.client.shared.help.FormHelpPanel; import org.jboss.as.console.client.widgets.ContentDescription; import org.jboss.as.console.client.widgets.forms.BlankItem; import org.jboss.as.console.client.widgets.forms.FormToolStrip; import org.jboss.ballroom.client.widgets.ContentGroupLabel; import org.jboss.ballroom.client.widgets.ContentHeaderLabel; import org.jboss.ballroom.client.widgets.forms.CheckBoxItem; import org.jboss.ballroom.client.widgets.forms.ComboBoxItem; import org.jboss.ballroom.client.widgets.forms.DisclosureGroupRenderer; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextBoxItem; import org.jboss.ballroom.client.widgets.forms.TextItem; import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; import org.jboss.ballroom.client.widgets.tabs.FakeTabPanel; import org.jboss.ballroom.client.widgets.tools.ToolButton; import org.jboss.ballroom.client.widgets.tools.ToolStrip; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; import java.util.List; import java.util.Map; /** * @author Heiko Braun * @date 10/24/11 */ public class InterfaceEditor { private DefaultCellTable<Interface> table; private ListDataProvider<Interface> dataProvider; private String title; private String description = null; private InterfaceManagement presenter; private Form<Interface> form; private ComboBoxItem anyAddress; public InterfaceEditor(String title) { this.title = title; } public void setDescription(String description) { this.description = description; } public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); FakeTabPanel titleBar = new FakeTabPanel(title); layout.add(titleBar); form = new Form<Interface>(Interface.class); ToolStrip topLevelTools = new ToolStrip(); ToolButton addBtn = new ToolButton(Console.CONSTANTS.common_label_add() , new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewInterfaceDialogue(); } }); addBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_add_interfaceEditor()); topLevelTools.addToolButtonRight(addBtn); ToolButton removeBtn = new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { final Interface editedEntity = form.getEditedEntity(); Feedback.confirm( Console.MESSAGES.deleteTitle("Interface"), Console.MESSAGES.deleteConfirm("Interface " + editedEntity.getName()), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if (isConfirmed) presenter.onRemoveInterface(editedEntity); } }); } }); removeBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_remove_interfaceEditor()); topLevelTools.addToolButtonRight(removeBtn); // ----------- VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); panel.add(new ContentHeaderLabel("Network Interfaces")); if(description!=null) { panel.add(new ContentDescription(description)); } panel.add(new ContentGroupLabel(Console.MESSAGES.available("Interfaces"))); table = new DefaultCellTable<Interface>(8, new ProvidesKey<Interface>() { @Override public Object getKey(Interface item) { return item.getName(); } }); dataProvider = new ListDataProvider<Interface>(); dataProvider.addDataDisplay(table); TextColumn<Interface> nameColumn = new TextColumn<Interface>() { @Override public String getValue(Interface record) { return record.getName(); } }; table.addColumn(nameColumn, "Name"); panel.add(topLevelTools); panel.add(table); panel.add(new ContentGroupLabel(Console.CONSTANTS.common_label_selection())); form.setNumColumns(2); TextItem nameItem = new TextItem("name", "Name"); TextBoxItem inetAddress = new TextBoxItem("inetAddress", "Inet Address", false); TextBoxItem nic = new TextBoxItem("nic", "Nic", false); TextBoxItem nicMatch = new TextBoxItem("nicMatch", "Nic Match", false); CheckBoxItem publicAddress = new CheckBoxItem("publicAddress", "Public Address"); CheckBoxItem siteLocalAddress = new CheckBoxItem("siteLocal", "Site Local Address"); CheckBoxItem linkLocalAddress = new CheckBoxItem("linkLocal", "Link Local Address"); anyAddress = new ComboBoxItem("addressWildcard", "Address Wildcard") { { isRequired = false; } }; anyAddress.setDefaultToFirstOption(true); anyAddress.setValueMap(new String[]{"", Interface.ANY_ADDRESS, Interface.ANY_IP4, Interface.ANY_IP6}); anyAddress.setValue(""); CheckBoxItem up = new CheckBoxItem("up", "Up"); CheckBoxItem virtual = new CheckBoxItem("virtual", "Virtual"); CheckBoxItem p2p = new CheckBoxItem("pointToPoint", "Point to Point"); CheckBoxItem multicast = new CheckBoxItem("multicast", "Multicast"); CheckBoxItem loopback = new CheckBoxItem("loopback", "Loopback"); TextBoxItem loopbackAddress = new TextBoxItem("loopbackAddress", "Loopback Address", false); form.setFields( nameItem, BlankItem.INSTANCE, inetAddress, anyAddress, nic, nicMatch, loopback, loopbackAddress); form.setFieldsInGroup( Console.CONSTANTS.common_label_advanced(), new DisclosureGroupRenderer(), up, virtual, publicAddress, siteLocalAddress, linkLocalAddress, multicast, p2p ); - FormToolStrip<Interface> toolstrip = new FormToolStrip<Interface>( + final FormToolStrip<Interface> toolstrip = new FormToolStrip<Interface>( form, new FormToolStrip.FormCallback<Interface>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveInterface(form.getUpdatedEntity(), changeset); } @Override public void onDelete(Interface entity) { } }); final HTML errorMessages = new HTML(); errorMessages.setStyleName("error-panel"); toolstrip.providesDeleteOp(false); toolstrip.setPreValidation(new FormToolStrip.PreValidation() { @Override public boolean isValid() { ValidationResult validation = presenter.validateInterfaceConstraints( form.getUpdatedEntity(), form.getChangedValues() ); errorMessages.setHTML(""); if(!validation.isValid()) { SafeHtmlBuilder html = new SafeHtmlBuilder(); int i=0; for(String detail : validation.getMessages()) { if(i==0) html.appendHtmlConstant("<b>"); html.appendEscaped(detail).appendHtmlConstant("<br/>"); if(i==0) html.appendHtmlConstant("</b>"); i++; } //Feedback.alert("Invalid Interface Constraints", html.toSafeHtml()); errorMessages.setHTML(html.toSafeHtml()); } return validation.isValid(); } }); form.bind(table); form.setEnabled(false); FormHelpPanel helpPanel = new FormHelpPanel(new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.add("interface", "*"); return address; } }, form); panel.add(toolstrip.asWidget()); panel.add(helpPanel.asWidget()); panel.add(errorMessages); panel.add(form.asWidget()); // clear messages upon cancel toolstrip.getCancelButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { errorMessages.setHTML(""); + toolstrip.doCancel(); } }); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, 40, Style.Unit.PX, 100, Style.Unit.PCT); return layout; } public void setInterfaces(List<Interface> interfaces) { anyAddress.clearSelection(); form.clearValues(); dataProvider.setList(interfaces); table.selectDefaultEntity(); } public void setPresenter(InterfaceManagement presenter) { this.presenter = presenter; } }
false
true
public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); FakeTabPanel titleBar = new FakeTabPanel(title); layout.add(titleBar); form = new Form<Interface>(Interface.class); ToolStrip topLevelTools = new ToolStrip(); ToolButton addBtn = new ToolButton(Console.CONSTANTS.common_label_add() , new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewInterfaceDialogue(); } }); addBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_add_interfaceEditor()); topLevelTools.addToolButtonRight(addBtn); ToolButton removeBtn = new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { final Interface editedEntity = form.getEditedEntity(); Feedback.confirm( Console.MESSAGES.deleteTitle("Interface"), Console.MESSAGES.deleteConfirm("Interface " + editedEntity.getName()), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if (isConfirmed) presenter.onRemoveInterface(editedEntity); } }); } }); removeBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_remove_interfaceEditor()); topLevelTools.addToolButtonRight(removeBtn); // ----------- VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); panel.add(new ContentHeaderLabel("Network Interfaces")); if(description!=null) { panel.add(new ContentDescription(description)); } panel.add(new ContentGroupLabel(Console.MESSAGES.available("Interfaces"))); table = new DefaultCellTable<Interface>(8, new ProvidesKey<Interface>() { @Override public Object getKey(Interface item) { return item.getName(); } }); dataProvider = new ListDataProvider<Interface>(); dataProvider.addDataDisplay(table); TextColumn<Interface> nameColumn = new TextColumn<Interface>() { @Override public String getValue(Interface record) { return record.getName(); } }; table.addColumn(nameColumn, "Name"); panel.add(topLevelTools); panel.add(table); panel.add(new ContentGroupLabel(Console.CONSTANTS.common_label_selection())); form.setNumColumns(2); TextItem nameItem = new TextItem("name", "Name"); TextBoxItem inetAddress = new TextBoxItem("inetAddress", "Inet Address", false); TextBoxItem nic = new TextBoxItem("nic", "Nic", false); TextBoxItem nicMatch = new TextBoxItem("nicMatch", "Nic Match", false); CheckBoxItem publicAddress = new CheckBoxItem("publicAddress", "Public Address"); CheckBoxItem siteLocalAddress = new CheckBoxItem("siteLocal", "Site Local Address"); CheckBoxItem linkLocalAddress = new CheckBoxItem("linkLocal", "Link Local Address"); anyAddress = new ComboBoxItem("addressWildcard", "Address Wildcard") { { isRequired = false; } }; anyAddress.setDefaultToFirstOption(true); anyAddress.setValueMap(new String[]{"", Interface.ANY_ADDRESS, Interface.ANY_IP4, Interface.ANY_IP6}); anyAddress.setValue(""); CheckBoxItem up = new CheckBoxItem("up", "Up"); CheckBoxItem virtual = new CheckBoxItem("virtual", "Virtual"); CheckBoxItem p2p = new CheckBoxItem("pointToPoint", "Point to Point"); CheckBoxItem multicast = new CheckBoxItem("multicast", "Multicast"); CheckBoxItem loopback = new CheckBoxItem("loopback", "Loopback"); TextBoxItem loopbackAddress = new TextBoxItem("loopbackAddress", "Loopback Address", false); form.setFields( nameItem, BlankItem.INSTANCE, inetAddress, anyAddress, nic, nicMatch, loopback, loopbackAddress); form.setFieldsInGroup( Console.CONSTANTS.common_label_advanced(), new DisclosureGroupRenderer(), up, virtual, publicAddress, siteLocalAddress, linkLocalAddress, multicast, p2p ); FormToolStrip<Interface> toolstrip = new FormToolStrip<Interface>( form, new FormToolStrip.FormCallback<Interface>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveInterface(form.getUpdatedEntity(), changeset); } @Override public void onDelete(Interface entity) { } }); final HTML errorMessages = new HTML(); errorMessages.setStyleName("error-panel"); toolstrip.providesDeleteOp(false); toolstrip.setPreValidation(new FormToolStrip.PreValidation() { @Override public boolean isValid() { ValidationResult validation = presenter.validateInterfaceConstraints( form.getUpdatedEntity(), form.getChangedValues() ); errorMessages.setHTML(""); if(!validation.isValid()) { SafeHtmlBuilder html = new SafeHtmlBuilder(); int i=0; for(String detail : validation.getMessages()) { if(i==0) html.appendHtmlConstant("<b>"); html.appendEscaped(detail).appendHtmlConstant("<br/>"); if(i==0) html.appendHtmlConstant("</b>"); i++; } //Feedback.alert("Invalid Interface Constraints", html.toSafeHtml()); errorMessages.setHTML(html.toSafeHtml()); } return validation.isValid(); } }); form.bind(table); form.setEnabled(false); FormHelpPanel helpPanel = new FormHelpPanel(new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.add("interface", "*"); return address; } }, form); panel.add(toolstrip.asWidget()); panel.add(helpPanel.asWidget()); panel.add(errorMessages); panel.add(form.asWidget()); // clear messages upon cancel toolstrip.getCancelButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { errorMessages.setHTML(""); } }); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, 40, Style.Unit.PX, 100, Style.Unit.PCT); return layout; }
public Widget asWidget() { LayoutPanel layout = new LayoutPanel(); FakeTabPanel titleBar = new FakeTabPanel(title); layout.add(titleBar); form = new Form<Interface>(Interface.class); ToolStrip topLevelTools = new ToolStrip(); ToolButton addBtn = new ToolButton(Console.CONSTANTS.common_label_add() , new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewInterfaceDialogue(); } }); addBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_add_interfaceEditor()); topLevelTools.addToolButtonRight(addBtn); ToolButton removeBtn = new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { final Interface editedEntity = form.getEditedEntity(); Feedback.confirm( Console.MESSAGES.deleteTitle("Interface"), Console.MESSAGES.deleteConfirm("Interface " + editedEntity.getName()), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if (isConfirmed) presenter.onRemoveInterface(editedEntity); } }); } }); removeBtn.ensureDebugId(Console.DEBUG_CONSTANTS.debug_label_remove_interfaceEditor()); topLevelTools.addToolButtonRight(removeBtn); // ----------- VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); panel.add(new ContentHeaderLabel("Network Interfaces")); if(description!=null) { panel.add(new ContentDescription(description)); } panel.add(new ContentGroupLabel(Console.MESSAGES.available("Interfaces"))); table = new DefaultCellTable<Interface>(8, new ProvidesKey<Interface>() { @Override public Object getKey(Interface item) { return item.getName(); } }); dataProvider = new ListDataProvider<Interface>(); dataProvider.addDataDisplay(table); TextColumn<Interface> nameColumn = new TextColumn<Interface>() { @Override public String getValue(Interface record) { return record.getName(); } }; table.addColumn(nameColumn, "Name"); panel.add(topLevelTools); panel.add(table); panel.add(new ContentGroupLabel(Console.CONSTANTS.common_label_selection())); form.setNumColumns(2); TextItem nameItem = new TextItem("name", "Name"); TextBoxItem inetAddress = new TextBoxItem("inetAddress", "Inet Address", false); TextBoxItem nic = new TextBoxItem("nic", "Nic", false); TextBoxItem nicMatch = new TextBoxItem("nicMatch", "Nic Match", false); CheckBoxItem publicAddress = new CheckBoxItem("publicAddress", "Public Address"); CheckBoxItem siteLocalAddress = new CheckBoxItem("siteLocal", "Site Local Address"); CheckBoxItem linkLocalAddress = new CheckBoxItem("linkLocal", "Link Local Address"); anyAddress = new ComboBoxItem("addressWildcard", "Address Wildcard") { { isRequired = false; } }; anyAddress.setDefaultToFirstOption(true); anyAddress.setValueMap(new String[]{"", Interface.ANY_ADDRESS, Interface.ANY_IP4, Interface.ANY_IP6}); anyAddress.setValue(""); CheckBoxItem up = new CheckBoxItem("up", "Up"); CheckBoxItem virtual = new CheckBoxItem("virtual", "Virtual"); CheckBoxItem p2p = new CheckBoxItem("pointToPoint", "Point to Point"); CheckBoxItem multicast = new CheckBoxItem("multicast", "Multicast"); CheckBoxItem loopback = new CheckBoxItem("loopback", "Loopback"); TextBoxItem loopbackAddress = new TextBoxItem("loopbackAddress", "Loopback Address", false); form.setFields( nameItem, BlankItem.INSTANCE, inetAddress, anyAddress, nic, nicMatch, loopback, loopbackAddress); form.setFieldsInGroup( Console.CONSTANTS.common_label_advanced(), new DisclosureGroupRenderer(), up, virtual, publicAddress, siteLocalAddress, linkLocalAddress, multicast, p2p ); final FormToolStrip<Interface> toolstrip = new FormToolStrip<Interface>( form, new FormToolStrip.FormCallback<Interface>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveInterface(form.getUpdatedEntity(), changeset); } @Override public void onDelete(Interface entity) { } }); final HTML errorMessages = new HTML(); errorMessages.setStyleName("error-panel"); toolstrip.providesDeleteOp(false); toolstrip.setPreValidation(new FormToolStrip.PreValidation() { @Override public boolean isValid() { ValidationResult validation = presenter.validateInterfaceConstraints( form.getUpdatedEntity(), form.getChangedValues() ); errorMessages.setHTML(""); if(!validation.isValid()) { SafeHtmlBuilder html = new SafeHtmlBuilder(); int i=0; for(String detail : validation.getMessages()) { if(i==0) html.appendHtmlConstant("<b>"); html.appendEscaped(detail).appendHtmlConstant("<br/>"); if(i==0) html.appendHtmlConstant("</b>"); i++; } //Feedback.alert("Invalid Interface Constraints", html.toSafeHtml()); errorMessages.setHTML(html.toSafeHtml()); } return validation.isValid(); } }); form.bind(table); form.setEnabled(false); FormHelpPanel helpPanel = new FormHelpPanel(new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = new ModelNode(); address.add("interface", "*"); return address; } }, form); panel.add(toolstrip.asWidget()); panel.add(helpPanel.asWidget()); panel.add(errorMessages); panel.add(form.asWidget()); // clear messages upon cancel toolstrip.getCancelButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { errorMessages.setHTML(""); toolstrip.doCancel(); } }); ScrollPanel scroll = new ScrollPanel(panel); layout.add(scroll); layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 40, Style.Unit.PX); layout.setWidgetTopHeight(scroll, 40, Style.Unit.PX, 100, Style.Unit.PCT); return layout; }
diff --git a/EEG/src/PatternGame/DataCollector.java b/EEG/src/PatternGame/DataCollector.java index 4732bb3..9a75502 100644 --- a/EEG/src/PatternGame/DataCollector.java +++ b/EEG/src/PatternGame/DataCollector.java @@ -1,199 +1,199 @@ package PatternGame; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import SDK.Edk; import SDK.EdkErrorCode; import SDK.EmoState; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; /* * Initializes the connection to the Emotiv device in * preparation for raw data collection. The Majority of this code * was provided by Emotiv and modified for our needs. */ public class DataCollector extends Thread { private String fileName = null; private Pointer eState = null; private Pointer eEvent = null; private BufferedWriter out = null; public boolean collecting; public boolean writingMatrix; private Matrix matrix; private int sample; /* * Initializes and starts the thread of execution */ public DataCollector(String threadName, String fileName) { super(threadName); this.fileName = fileName; start(); } /* * The threads main flow of execution. Initializes the Emotiv device and * then reads data from the sensors. This data is constantly written to the * file specified by fileName. Also, writes sensor data to the Matrix object * matrix when set to do so. * */ public void run() { /*Initialization*/ eEvent = Edk.INSTANCE.EE_EmoEngineEventCreate(); eState = Edk.INSTANCE.EE_EmoStateCreate(); IntByReference userID = null; IntByReference nSamplesTaken= null; int state = 0; float secs = 60; boolean readytocollect = false; collecting = true; writingMatrix = false; userID = new IntByReference(0); nSamplesTaken = new IntByReference(0); /*Initialize the text file we are printing to for the visualization data*/ try { out = new BufferedWriter(new FileWriter("VisualizationData/" + fileName + ".txt")); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } if (Edk.INSTANCE.EE_EngineConnect("Emotiv Systems-5") != EdkErrorCode.EDK_OK.ToInt()) { System.err.println("Emotiv Engine start up failed."); return; } Pointer hData = Edk.INSTANCE.EE_DataCreate(); Edk.INSTANCE.EE_DataSetBufferSizeInSec(secs); System.out.println("Started receiving EEG Data!"); while (collecting) { state = Edk.INSTANCE.EE_EngineGetNextEvent(eEvent); // New event needs to be handled if (state == EdkErrorCode.EDK_OK.ToInt()) { int eventType = Edk.INSTANCE.EE_EmoEngineEventGetType(eEvent); Edk.INSTANCE.EE_EmoEngineEventGetUserId(eEvent, userID); // Log the EmoState if it has been updated if (eventType == Edk.EE_Event_t.EE_UserAdded.ToInt()) { if (userID != null) { System.out.println("User added"); Edk.INSTANCE.EE_DataAcquisitionEnable(userID.getValue(),true); readytocollect = true; } } if (eventType == Edk.EE_Event_t.EE_EmoStateUpdated.ToInt()) { Edk.INSTANCE.EE_EmoEngineEventGetEmoState(eEvent, eState); } } else if (state != EdkErrorCode.EDK_NO_EVENT.ToInt()) { System.err.println("Internal error in Emotiv Engine!"); break; } if (readytocollect) { //get the data from device Edk.INSTANCE.EE_DataUpdateHandle(0, hData); Edk.INSTANCE.EE_DataGetNumberOfSample(hData, nSamplesTaken); if (nSamplesTaken != null) { if (nSamplesTaken.getValue() != 0) { double[] data = new double[nSamplesTaken.getValue()]; for (int sampleIdx=0 ; sampleIdx < nSamplesTaken.getValue(); ++sampleIdx) { try { //write the millisecond time stamp Edk.INSTANCE.EE_DataGet(hData, 19, data, nSamplesTaken.getValue()); //The millisecond column out.write(Integer.toString((int) (data[sampleIdx] * 1000)) + " "); //loop through the the data columns for (int i = 0 ; i < 25 ; i++) { Edk.INSTANCE.EE_DataGet(hData, i, data, nSamplesTaken.getValue()); if ( writingMatrix && i >= 3 && i <= 16) { try { matrix.matrix[sample][i-3] = data[sampleIdx]; } catch (ArrayIndexOutOfBoundsException e) { writingMatrix = false; } } //Write the column data to the file out.write( Double.toString((data[sampleIdx]))); out.write(" "); } //increment the sample if(writingMatrix) sample++; //write key indicator column - out.write("0"); + out.write((writingMatrix)? "1" : "0"); //Print the contact quality columns to our file //The ordering is consistent with the ordering of the logical input //channels in EE_InputChannels_enum. for (int i = 1; i < 15 ; i++) out.write(" " + EmoState.INSTANCE.ES_GetContactQuality(eState, i) + " "); //next row out.newLine(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } }//END for() } } } //END if(ready to collect) } //END while cleanUp(); } /* * Creates a Matrix object of size seconds and * sets the thread to fill it with data until * full. */ public void setMatrix(int seconds) { this.matrix = new Matrix(seconds); this.sample = 0; this.writingMatrix = true; } /* * returns the matrix object */ public Matrix getMatrix() { return this.matrix; } /* * Shuts down the Emotiv connection * Frees the eState and eEvent memory */ public void cleanUp() { //close all connections; try { out.close(); } catch (IOException e) { System.err.println(e.getMessage()); } Edk.INSTANCE.EE_EngineDisconnect(); Edk.INSTANCE.EE_EmoStateFree(eState); Edk.INSTANCE.EE_EmoEngineEventFree(eEvent); } }
true
true
public void run() { /*Initialization*/ eEvent = Edk.INSTANCE.EE_EmoEngineEventCreate(); eState = Edk.INSTANCE.EE_EmoStateCreate(); IntByReference userID = null; IntByReference nSamplesTaken= null; int state = 0; float secs = 60; boolean readytocollect = false; collecting = true; writingMatrix = false; userID = new IntByReference(0); nSamplesTaken = new IntByReference(0); /*Initialize the text file we are printing to for the visualization data*/ try { out = new BufferedWriter(new FileWriter("VisualizationData/" + fileName + ".txt")); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } if (Edk.INSTANCE.EE_EngineConnect("Emotiv Systems-5") != EdkErrorCode.EDK_OK.ToInt()) { System.err.println("Emotiv Engine start up failed."); return; } Pointer hData = Edk.INSTANCE.EE_DataCreate(); Edk.INSTANCE.EE_DataSetBufferSizeInSec(secs); System.out.println("Started receiving EEG Data!"); while (collecting) { state = Edk.INSTANCE.EE_EngineGetNextEvent(eEvent); // New event needs to be handled if (state == EdkErrorCode.EDK_OK.ToInt()) { int eventType = Edk.INSTANCE.EE_EmoEngineEventGetType(eEvent); Edk.INSTANCE.EE_EmoEngineEventGetUserId(eEvent, userID); // Log the EmoState if it has been updated if (eventType == Edk.EE_Event_t.EE_UserAdded.ToInt()) { if (userID != null) { System.out.println("User added"); Edk.INSTANCE.EE_DataAcquisitionEnable(userID.getValue(),true); readytocollect = true; } } if (eventType == Edk.EE_Event_t.EE_EmoStateUpdated.ToInt()) { Edk.INSTANCE.EE_EmoEngineEventGetEmoState(eEvent, eState); } } else if (state != EdkErrorCode.EDK_NO_EVENT.ToInt()) { System.err.println("Internal error in Emotiv Engine!"); break; } if (readytocollect) { //get the data from device Edk.INSTANCE.EE_DataUpdateHandle(0, hData); Edk.INSTANCE.EE_DataGetNumberOfSample(hData, nSamplesTaken); if (nSamplesTaken != null) { if (nSamplesTaken.getValue() != 0) { double[] data = new double[nSamplesTaken.getValue()]; for (int sampleIdx=0 ; sampleIdx < nSamplesTaken.getValue(); ++sampleIdx) { try { //write the millisecond time stamp Edk.INSTANCE.EE_DataGet(hData, 19, data, nSamplesTaken.getValue()); //The millisecond column out.write(Integer.toString((int) (data[sampleIdx] * 1000)) + " "); //loop through the the data columns for (int i = 0 ; i < 25 ; i++) { Edk.INSTANCE.EE_DataGet(hData, i, data, nSamplesTaken.getValue()); if ( writingMatrix && i >= 3 && i <= 16) { try { matrix.matrix[sample][i-3] = data[sampleIdx]; } catch (ArrayIndexOutOfBoundsException e) { writingMatrix = false; } } //Write the column data to the file out.write( Double.toString((data[sampleIdx]))); out.write(" "); } //increment the sample if(writingMatrix) sample++; //write key indicator column out.write("0"); //Print the contact quality columns to our file //The ordering is consistent with the ordering of the logical input //channels in EE_InputChannels_enum. for (int i = 1; i < 15 ; i++) out.write(" " + EmoState.INSTANCE.ES_GetContactQuality(eState, i) + " "); //next row out.newLine(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } }//END for() } } } //END if(ready to collect) } //END while cleanUp(); }
public void run() { /*Initialization*/ eEvent = Edk.INSTANCE.EE_EmoEngineEventCreate(); eState = Edk.INSTANCE.EE_EmoStateCreate(); IntByReference userID = null; IntByReference nSamplesTaken= null; int state = 0; float secs = 60; boolean readytocollect = false; collecting = true; writingMatrix = false; userID = new IntByReference(0); nSamplesTaken = new IntByReference(0); /*Initialize the text file we are printing to for the visualization data*/ try { out = new BufferedWriter(new FileWriter("VisualizationData/" + fileName + ".txt")); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } if (Edk.INSTANCE.EE_EngineConnect("Emotiv Systems-5") != EdkErrorCode.EDK_OK.ToInt()) { System.err.println("Emotiv Engine start up failed."); return; } Pointer hData = Edk.INSTANCE.EE_DataCreate(); Edk.INSTANCE.EE_DataSetBufferSizeInSec(secs); System.out.println("Started receiving EEG Data!"); while (collecting) { state = Edk.INSTANCE.EE_EngineGetNextEvent(eEvent); // New event needs to be handled if (state == EdkErrorCode.EDK_OK.ToInt()) { int eventType = Edk.INSTANCE.EE_EmoEngineEventGetType(eEvent); Edk.INSTANCE.EE_EmoEngineEventGetUserId(eEvent, userID); // Log the EmoState if it has been updated if (eventType == Edk.EE_Event_t.EE_UserAdded.ToInt()) { if (userID != null) { System.out.println("User added"); Edk.INSTANCE.EE_DataAcquisitionEnable(userID.getValue(),true); readytocollect = true; } } if (eventType == Edk.EE_Event_t.EE_EmoStateUpdated.ToInt()) { Edk.INSTANCE.EE_EmoEngineEventGetEmoState(eEvent, eState); } } else if (state != EdkErrorCode.EDK_NO_EVENT.ToInt()) { System.err.println("Internal error in Emotiv Engine!"); break; } if (readytocollect) { //get the data from device Edk.INSTANCE.EE_DataUpdateHandle(0, hData); Edk.INSTANCE.EE_DataGetNumberOfSample(hData, nSamplesTaken); if (nSamplesTaken != null) { if (nSamplesTaken.getValue() != 0) { double[] data = new double[nSamplesTaken.getValue()]; for (int sampleIdx=0 ; sampleIdx < nSamplesTaken.getValue(); ++sampleIdx) { try { //write the millisecond time stamp Edk.INSTANCE.EE_DataGet(hData, 19, data, nSamplesTaken.getValue()); //The millisecond column out.write(Integer.toString((int) (data[sampleIdx] * 1000)) + " "); //loop through the the data columns for (int i = 0 ; i < 25 ; i++) { Edk.INSTANCE.EE_DataGet(hData, i, data, nSamplesTaken.getValue()); if ( writingMatrix && i >= 3 && i <= 16) { try { matrix.matrix[sample][i-3] = data[sampleIdx]; } catch (ArrayIndexOutOfBoundsException e) { writingMatrix = false; } } //Write the column data to the file out.write( Double.toString((data[sampleIdx]))); out.write(" "); } //increment the sample if(writingMatrix) sample++; //write key indicator column out.write((writingMatrix)? "1" : "0"); //Print the contact quality columns to our file //The ordering is consistent with the ordering of the logical input //channels in EE_InputChannels_enum. for (int i = 1; i < 15 ; i++) out.write(" " + EmoState.INSTANCE.ES_GetContactQuality(eState, i) + " "); //next row out.newLine(); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } }//END for() } } } //END if(ready to collect) } //END while cleanUp(); }
diff --git a/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java b/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java index cb2b8d0a0..5af58b8f8 100644 --- a/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java +++ b/dspace-api/src/main/java/org/dspace/browse/ItemCounter.java @@ -1,291 +1,291 @@ /* * ItemCounter.java * * Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.browse; import org.apache.log4j.Logger; import org.dspace.content.Community; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; import java.sql.SQLException; /** * This class provides a standard interface to all item counting * operations for communities and collections. It can be run from the * command line to prepare the cached data if desired, simply by * running: * * java org.dspace.browse.ItemCounter * * It can also be invoked via its standard API. In the event that * the data cache is not being used, this class will return direct * real time counts of content. * * @author Richard Jones * */ public class ItemCounter { /** Log4j logger */ private static Logger log = Logger.getLogger(ItemCounter.class); /** DAO to use to store and retrieve data */ private ItemCountDAO dao; /** DSpace Context */ private Context context; /** * method invoked by CLI which will result in the number of items * in each community and collection being cached. These counts will * not update themselves until this is run again. * * @param args */ public static void main(String[] args) throws ItemCountException { ItemCounter ic = new ItemCounter(); ic.buildItemCounts(); ic.completeContext(); } /** * Construct a new item counter which will create its own * DSpace Context * * @throws ItemCountException */ public ItemCounter() throws ItemCountException { try { this.context = new Context(); this.dao = ItemCountDAOFactory.getInstance(this.context); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Construct a new item counter which will use the give DSpace Context * * @param context * @throws ItemCountException */ public ItemCounter(Context context) throws ItemCountException { this.context = context; this.dao = ItemCountDAOFactory.getInstance(this.context); } /** * Complete the context being used by this class. This exists so that * instances of this class which created their own instance of the * DSpace Context can also terminate it. For Context object which were * passed in by the constructor, the caller is responsible for * either calling this method themselves or completing the context * when they need to. * * @throws ItemCountException */ public void completeContext() throws ItemCountException { try { this.context.complete(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * This method does the grunt work of drilling through and iterating * over all of the communities and collections in the system and * obtaining and caching the item counts for each one. * * @throws ItemCountException */ public void buildItemCounts() throws ItemCountException { try { Community[] tlc = Community.findAllTop(context); for (int i = 0; i < tlc.length; i++) { count(tlc[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * Get the count of the items in the given container. If the configuration * value webui.strengths.cache is equal to 'true' this will return the * cached value if it exists. If it is equal to 'false' it will count * the number of items in the container in real time * * @param dso * @return * @throws ItemCountException * @throws SQLException */ public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { - return ((Collection) dso).countItems(); + return ((Community) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; } /** * Remove any cached data for the given container * * @param dso * @throws ItemCountException */ public void remove(DSpaceObject dso) throws ItemCountException { dao.remove(dso); } /** * count and cache the number of items in the community. This * will include all sub-communities and collections in the * community. It will also recurse into sub-communities and * collections and call count() on them also. * * Therefore, the count the contents of the entire system, it is * necessary just to call this method on each top level community * * @param community * @throws ItemCountException */ private void count(Community community) throws ItemCountException { try { // first count the community we are in int count = community.countItems(); dao.communityCount(community, count); // now get the sub-communities Community[] scs = community.getSubcommunities(); for (int i = 0; i < scs.length; i++) { count(scs[i]); } // now get the collections Collection[] cols = community.getCollections(); for (int i = 0; i < cols.length; i++) { count(cols[i]); } } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } /** * count and cache the number of items in the given collection * * @param collection * @throws ItemCountException */ private void count(Collection collection) throws ItemCountException { try { int ccount = collection.countItems(); dao.collectionCount(collection, ccount); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } }
true
true
public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; }
public int getCount(DSpaceObject dso) throws ItemCountException { boolean useCache = ConfigurationManager.getBooleanProperty("webui.strengths.cache"); if (useCache) { return dao.getCount(dso); } // if we make it this far, we need to manually count if (dso instanceof Collection) { try { return ((Collection) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } if (dso instanceof Community) { try { return ((Community) dso).countItems(); } catch (SQLException e) { log.error("caught exception: ", e); throw new ItemCountException(e); } } return 0; }
diff --git a/lucene/src/test/org/apache/lucene/search/TestWildcard.java b/lucene/src/test/org/apache/lucene/search/TestWildcard.java index 56e2825e6..22f4cc52c 100644 --- a/lucene/src/test/org/apache/lucene/search/TestWildcard.java +++ b/lucene/src/test/org/apache/lucene/search/TestWildcard.java @@ -1,358 +1,360 @@ package org.apache.lucene.search; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.Index; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.Terms; import org.apache.lucene.queryParser.QueryParser; import java.io.IOException; /** * TestWildcard tests the '*' and '?' wildcard characters. */ public class TestWildcard extends LuceneTestCase { @Override public void setUp() throws Exception { super.setUp(); } public void testEquals() { WildcardQuery wq1 = new WildcardQuery(new Term("field", "b*a")); WildcardQuery wq2 = new WildcardQuery(new Term("field", "b*a")); WildcardQuery wq3 = new WildcardQuery(new Term("field", "b*a")); // reflexive? assertEquals(wq1, wq2); assertEquals(wq2, wq1); // transitive? assertEquals(wq2, wq3); assertEquals(wq1, wq3); assertFalse(wq1.equals(null)); FuzzyQuery fq = new FuzzyQuery(new Term("field", "b*a")); assertFalse(wq1.equals(fq)); assertFalse(fq.equals(wq1)); } /** * Tests if a WildcardQuery that has no wildcard in the term is rewritten to a single * TermQuery. The boost should be preserved, and the rewrite should return * a ConstantScoreQuery if the WildcardQuery had a ConstantScore rewriteMethod. */ public void testTermWithoutWildcard() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"nowildcard", "nowildcardx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "nowildcard")); assertMatches(searcher, wq, 1); wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.1F); Query q = searcher.rewrite(wq); assertTrue(q instanceof TermQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); wq.setBoost(0.2F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT); wq.setBoost(0.3F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); wq.setRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); wq.setBoost(0.4F); q = searcher.rewrite(wq); assertTrue(q instanceof ConstantScoreQuery); assertEquals(q.getBoost(), wq.getBoost()); searcher.close(); indexStore.close(); } /** * Tests if a WildcardQuery with an empty term is rewritten to an empty BooleanQuery */ public void testEmptyTerm() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"nowildcard", "nowildcardx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "")); wq.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE); assertMatches(searcher, wq, 0); Query q = searcher.rewrite(wq); assertTrue(q instanceof BooleanQuery); assertEquals(0, ((BooleanQuery) q).clauses().size()); searcher.close(); indexStore.close(); } /** * Tests if a WildcardQuery that has only a trailing * in the term is * rewritten to a single PrefixQuery. The boost and rewriteMethod should be * preserved. */ public void testPrefixTerm() throws IOException { Directory indexStore = getIndexStore("field", new String[]{"prefix", "prefixx"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); MultiTermQuery wq = new WildcardQuery(new Term("field", "prefix*")); assertMatches(searcher, wq, 2); Terms terms = MultiFields.getTerms(searcher.getIndexReader(), "field"); assertTrue(wq.getTermsEnum(terms) instanceof PrefixTermsEnum); wq = new WildcardQuery(new Term("field", "*")); assertMatches(searcher, wq, 2); assertFalse(wq.getTermsEnum(terms) instanceof PrefixTermsEnum); assertFalse(wq.getTermsEnum(terms) instanceof AutomatonTermsEnum); searcher.close(); indexStore.close(); } /** * Tests Wildcard queries with an asterisk. */ public void testAsterisk() throws IOException { Directory indexStore = getIndexStore("body", new String[] {"metal", "metals"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); Query query1 = new TermQuery(new Term("body", "metal")); Query query2 = new WildcardQuery(new Term("body", "metal*")); Query query3 = new WildcardQuery(new Term("body", "m*tal")); Query query4 = new WildcardQuery(new Term("body", "m*tal*")); Query query5 = new WildcardQuery(new Term("body", "m*tals")); BooleanQuery query6 = new BooleanQuery(); query6.add(query5, BooleanClause.Occur.SHOULD); BooleanQuery query7 = new BooleanQuery(); query7.add(query3, BooleanClause.Occur.SHOULD); query7.add(query5, BooleanClause.Occur.SHOULD); // Queries do not automatically lower-case search terms: Query query8 = new WildcardQuery(new Term("body", "M*tal*")); assertMatches(searcher, query1, 1); assertMatches(searcher, query2, 2); assertMatches(searcher, query3, 1); assertMatches(searcher, query4, 2); assertMatches(searcher, query5, 1); assertMatches(searcher, query6, 1); assertMatches(searcher, query7, 2); assertMatches(searcher, query8, 0); assertMatches(searcher, new WildcardQuery(new Term("body", "*tall")), 0); assertMatches(searcher, new WildcardQuery(new Term("body", "*tal")), 1); assertMatches(searcher, new WildcardQuery(new Term("body", "*tal*")), 2); searcher.close(); indexStore.close(); } /** * Tests Wildcard queries with a question mark. * * @throws IOException if an error occurs */ public void testQuestionmark() throws IOException { Directory indexStore = getIndexStore("body", new String[] {"metal", "metals", "mXtals", "mXtXls"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); Query query1 = new WildcardQuery(new Term("body", "m?tal")); Query query2 = new WildcardQuery(new Term("body", "metal?")); Query query3 = new WildcardQuery(new Term("body", "metals?")); Query query4 = new WildcardQuery(new Term("body", "m?t?ls")); Query query5 = new WildcardQuery(new Term("body", "M?t?ls")); Query query6 = new WildcardQuery(new Term("body", "meta??")); assertMatches(searcher, query1, 1); assertMatches(searcher, query2, 1); assertMatches(searcher, query3, 0); assertMatches(searcher, query4, 3); assertMatches(searcher, query5, 0); assertMatches(searcher, query6, 1); // Query: 'meta??' matches 'metals' not 'metal' searcher.close(); indexStore.close(); } /** * Tests if wildcard escaping works */ public void testEscapes() throws Exception { Directory indexStore = getIndexStore("field", new String[]{"foo*bar", "foo??bar", "fooCDbar", "fooSOMETHINGbar", "foo\\"}); IndexSearcher searcher = new IndexSearcher(indexStore, true); // without escape: matches foo??bar, fooCDbar, foo*bar, and fooSOMETHINGbar WildcardQuery unescaped = new WildcardQuery(new Term("field", "foo*bar")); assertMatches(searcher, unescaped, 4); // with escape: only matches foo*bar WildcardQuery escaped = new WildcardQuery(new Term("field", "foo\\*bar")); assertMatches(searcher, escaped, 1); // without escape: matches foo??bar and fooCDbar unescaped = new WildcardQuery(new Term("field", "foo??bar")); assertMatches(searcher, unescaped, 2); // with escape: matches foo??bar only escaped = new WildcardQuery(new Term("field", "foo\\?\\?bar")); assertMatches(searcher, escaped, 1); // check escaping at end: lenient parse yields "foo\" WildcardQuery atEnd = new WildcardQuery(new Term("field", "foo\\")); assertMatches(searcher, atEnd, 1); searcher.close(); indexStore.close(); } private Directory getIndexStore(String field, String[] contents) throws IOException { Directory indexStore = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, indexStore); for (int i = 0; i < contents.length; ++i) { Document doc = new Document(); doc.add(newField(field, contents[i], Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } writer.close(); return indexStore; } private void assertMatches(IndexSearcher searcher, Query q, int expectedMatches) throws IOException { ScoreDoc[] result = searcher.search(q, null, 1000).scoreDocs; assertEquals(expectedMatches, result.length); } /** * Test that wild card queries are parsed to the correct type and are searched correctly. * This test looks at both parsing and execution of wildcard queries. * Although placed here, it also tests prefix queries, verifying that * prefix queries are not parsed into wild card queries, and viceversa. * @throws Exception */ public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); - RandomIndexWriter iw = new RandomIndexWriter(random, dir); + RandomIndexWriter iw = new RandomIndexWriter(random, dir, + newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()) + .setMergePolicy(newInOrderLogMergePolicy())); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); } }
true
true
public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random, dir); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); }
public void testParsingAndSearching() throws Exception { String field = "content"; QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, field, new MockAnalyzer()); qp.setAllowLeadingWildcard(true); String docs[] = { "\\ abcdefg1", "\\79 hijklmn1", "\\\\ opqrstu1", }; // queries that should find all docs String matchAll[] = { "*", "*1", "**1", "*?", "*?1", "?*1", "**", "***", "\\\\*" }; // queries that should find no docs String matchNone[] = { "a*h", "a?h", "*a*h", "?a", "a?", }; // queries that should be parsed to prefix queries String matchOneDocPrefix[][] = { {"a*", "ab*", "abc*", }, // these should find only doc 0 {"h*", "hi*", "hij*", "\\\\7*"}, // these should find only doc 1 {"o*", "op*", "opq*", "\\\\\\\\*"}, // these should find only doc 2 }; // queries that should be parsed to wildcard queries String matchOneDocWild[][] = { {"*a*", "*ab*", "*abc**", "ab*e*", "*g?", "*f?1", "abc**"}, // these should find only doc 0 {"*h*", "*hi*", "*hij**", "hi*k*", "*n?", "*m?1", "hij**"}, // these should find only doc 1 {"*o*", "*op*", "*opq**", "op*q*", "*u?", "*t?1", "opq**"}, // these should find only doc 2 }; // prepare the index Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()) .setMergePolicy(newInOrderLogMergePolicy())); for (int i = 0; i < docs.length; i++) { Document doc = new Document(); doc.add(newField(field,docs[i],Store.NO,Index.ANALYZED)); iw.addDocument(doc); } iw.close(); IndexSearcher searcher = new IndexSearcher(dir, true); // test queries that must find all for (int i = 0; i < matchAll.length; i++) { String qtxt = matchAll[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchAll: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(docs.length,hits.length); } // test queries that must find none for (int i = 0; i < matchNone.length; i++) { String qtxt = matchNone[i]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("matchNone: qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(0,hits.length); } // test queries that must be prefix queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocPrefix[i].length; j++) { String qtxt = matchOneDocPrefix[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 prefix: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(PrefixQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } // test queries that must be wildcard queries and must find only one doc for (int i = 0; i < matchOneDocPrefix.length; i++) { for (int j = 0; j < matchOneDocWild[i].length; j++) { String qtxt = matchOneDocWild[i][j]; Query q = qp.parse(qtxt); if (VERBOSE) System.out.println("match 1 wild: doc="+docs[i]+" qtxt="+qtxt+" q="+q+" "+q.getClass().getName()); assertEquals(WildcardQuery.class, q.getClass()); ScoreDoc[] hits = searcher.search(q, null, 1000).scoreDocs; assertEquals(1,hits.length); assertEquals(i,hits[0].doc); } } searcher.close(); dir.close(); }
diff --git a/autocompleteServer/src/test/java/de/metalcon/autocompleteServer/Create/TestProcessCreateRequest.java b/autocompleteServer/src/test/java/de/metalcon/autocompleteServer/Create/TestProcessCreateRequest.java index 0af341b..9825746 100644 --- a/autocompleteServer/src/test/java/de/metalcon/autocompleteServer/Create/TestProcessCreateRequest.java +++ b/autocompleteServer/src/test/java/de/metalcon/autocompleteServer/Create/TestProcessCreateRequest.java @@ -1,89 +1,89 @@ package de.metalcon.autocompleteServer.Create; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import org.junit.Before; import org.junit.Test; import de.metalcon.autocompleteServer.Helper.ProtocolConstants; import de.metalcon.autocompleteServer.Helper.SuggestTree; import de.metalcon.utils.FormItemList; public class TestProcessCreateRequest { final private ServletConfig servletConfig = mock(ServletConfig.class); final private ServletContext servletContext = mock(ServletContext.class); private HttpServletRequest request; @Before public void initializeTest() { this.request = mock(HttpServletRequest.class); HttpServlet servlet = mock(HttpServlet.class); when(this.servletConfig.getServletContext()).thenReturn( this.servletContext); SuggestTree generalIndex = new SuggestTree(7); when( this.servletContext .getAttribute(ProtocolConstants.INDEX_PARAMETER + "testIndex")).thenReturn(generalIndex); try { servlet.init(this.servletConfig); } catch (ServletException e) { fail("could not initialize servlet"); e.printStackTrace(); } } // TODO: add tests according to protocol specifications. Check each possible // status. @Test public void testFullFormWithoutImage() { ProcessCreateResponse testResponse = this.processTestRequest( ProtocolTestConstants.VALID_SUGGESTION_KEY, ProtocolTestConstants.VALID_SUGGESTION_STRING, ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, ProtocolTestConstants.VALID_SUGGESTION_INDEX); assertEquals("{" + "\"term\"" + ":" + "\"test\"" + "," - + "\"Warning:noImage\"" + ":" + "No image inserted" + "}", + + "\"Warning:noImage\"" + ":" + "\"No image inserted\"" + "}", testResponse.getResponse().toString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_KEY, testResponse .getContainer().getKey()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_STRING, testResponse.getContainer().getSuggestString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, testResponse.getContainer().getWeight()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_INDEX, testResponse .getContainer().getIndexName()); } private ProcessCreateResponse processTestRequest(String key, String term, String weight, String index) { ProcessCreateResponse response = new ProcessCreateResponse( this.servletConfig.getServletContext()); FormItemList testItems = new FormItemList(); testItems.addField(ProtocolConstants.SUGGESTION_KEY, key); testItems.addField(ProtocolConstants.SUGGESTION_STRING, term); testItems.addField(ProtocolConstants.SUGGESTION_WEIGHT, weight); testItems.addField(ProtocolConstants.INDEX_PARAMETER, index); return ProcessCreateRequest.checkRequestParameter(testItems, response, this.servletConfig.getServletContext()); } }
true
true
public void testFullFormWithoutImage() { ProcessCreateResponse testResponse = this.processTestRequest( ProtocolTestConstants.VALID_SUGGESTION_KEY, ProtocolTestConstants.VALID_SUGGESTION_STRING, ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, ProtocolTestConstants.VALID_SUGGESTION_INDEX); assertEquals("{" + "\"term\"" + ":" + "\"test\"" + "," + "\"Warning:noImage\"" + ":" + "No image inserted" + "}", testResponse.getResponse().toString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_KEY, testResponse .getContainer().getKey()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_STRING, testResponse.getContainer().getSuggestString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, testResponse.getContainer().getWeight()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_INDEX, testResponse .getContainer().getIndexName()); }
public void testFullFormWithoutImage() { ProcessCreateResponse testResponse = this.processTestRequest( ProtocolTestConstants.VALID_SUGGESTION_KEY, ProtocolTestConstants.VALID_SUGGESTION_STRING, ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, ProtocolTestConstants.VALID_SUGGESTION_INDEX); assertEquals("{" + "\"term\"" + ":" + "\"test\"" + "," + "\"Warning:noImage\"" + ":" + "\"No image inserted\"" + "}", testResponse.getResponse().toString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_KEY, testResponse .getContainer().getKey()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_STRING, testResponse.getContainer().getSuggestString()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_WEIGHT, testResponse.getContainer().getWeight()); assertEquals(ProtocolTestConstants.VALID_SUGGESTION_INDEX, testResponse .getContainer().getIndexName()); }
diff --git a/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java b/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java index 521f7ef..fad9085 100755 --- a/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java +++ b/java/xbee/src/com/rapplogic/xbee/examples/RemoteAtExample.java @@ -1,125 +1,125 @@ /** * Copyright (c) 2008 Andrew Rapp. All rights reserved. * * This file is part of XBee-API. * * XBee-API is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * XBee-API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBee-API. If not, see <http://www.gnu.org/licenses/>. */ package com.rapplogic.xbee.examples; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.nfc.ryanjfahsel.DBConnection; import com.rapplogic.xbee.api.RemoteAtRequest; import com.rapplogic.xbee.api.RemoteAtResponse; import com.rapplogic.xbee.api.XBee; import com.rapplogic.xbee.api.XBeeAddress64; import com.rapplogic.xbee.api.XBeeException; import com.rapplogic.xbee.api.XBeeTimeoutException; /** * This example uses Remote AT to turn on/off I/O pins. * This example is more interesting if you connect a LED to pin 20 on your end device. * Remember to use a resistor to limit the current flow. I used a 215 Ohm resistor. * <p/> * Note: if your coordinator is powered on and receiving I/O samples, make sure you power off/on to drain * the traffic before running this example. * * @author andrew * */ public class RemoteAtExample { private final static Logger log = Logger.getLogger(RemoteAtExample.class); private RemoteAtExample() throws XBeeException, InterruptedException { XBee xbee = new XBee(); try { // replace with your coordinator com/baud String SerialPortID="/dev/ttyAMA0"; System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID); xbee.open(SerialPortID, 9600); // xbee.open("COM5", 9600); // replace with SH + SL of your end device XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF); // turn on end device (pin 20) D0 (Digital output high = 5) //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3}); RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned on pin 20 (D0)"); } else { throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus()); } - System.exit(0); + //System.exit(0); // wait a bit Thread.sleep(5000); // // // now turn off end device D0 request.setValue(new int[] {4}); response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned off pin 20 (D0)"); } else { throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus()); } } catch (XBeeTimeoutException e) { log.error("request timed out. make sure you remote XBee is configured and powered on"); } catch (Exception e) { log.error("unexpected error", e); } finally { - //xbee.close(); + xbee.close(); } } public static void main(String[] args) throws XBeeException, InterruptedException { PropertyConfigurator.configure("log4j.properties"); DBConnection conn=new DBConnection("admin","admin"); int result; int prevResult; result=Integer.parseInt(conn.Connect()); prevResult=Integer.parseInt(conn.Connect()); new RemoteAtExample(); Thread.sleep(7000); System.out.println("Enterring loop"); while(true) { result=Integer.parseInt(conn.Connect()); if(result==prevResult) { //Do nothing } else { new RemoteAtExample(); prevResult=result; } result=Integer.parseInt(conn.Connect()); Thread.sleep(1000); } } }
false
true
private RemoteAtExample() throws XBeeException, InterruptedException { XBee xbee = new XBee(); try { // replace with your coordinator com/baud String SerialPortID="/dev/ttyAMA0"; System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID); xbee.open(SerialPortID, 9600); // xbee.open("COM5", 9600); // replace with SH + SL of your end device XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF); // turn on end device (pin 20) D0 (Digital output high = 5) //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3}); RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned on pin 20 (D0)"); } else { throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus()); } System.exit(0); // wait a bit Thread.sleep(5000); // // // now turn off end device D0 request.setValue(new int[] {4}); response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned off pin 20 (D0)"); } else { throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus()); } } catch (XBeeTimeoutException e) { log.error("request timed out. make sure you remote XBee is configured and powered on"); } catch (Exception e) { log.error("unexpected error", e); } finally { //xbee.close(); } }
private RemoteAtExample() throws XBeeException, InterruptedException { XBee xbee = new XBee(); try { // replace with your coordinator com/baud String SerialPortID="/dev/ttyAMA0"; System.setProperty("gnu.io.rxtx.SerialPorts", SerialPortID); xbee.open(SerialPortID, 9600); // xbee.open("COM5", 9600); // replace with SH + SL of your end device XBeeAddress64 addr64 = new XBeeAddress64(0, 0x00, 0x00, 0, 0x00, 0x00, 0xFF, 0xFF); // turn on end device (pin 20) D0 (Digital output high = 5) //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "IR", new int[] {0x7f, 0xff}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D5", new int[] {3}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {2}); //RemoteAtRequest request = new RemoteAtRequest(addr64, "P2", new int[] {3}); RemoteAtRequest request = new RemoteAtRequest(addr64, "D0", new int[] {5}); RemoteAtResponse response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned on pin 20 (D0)"); } else { throw new RuntimeException("failed to turn on pin 20. status is " + response.getStatus()); } //System.exit(0); // wait a bit Thread.sleep(5000); // // // now turn off end device D0 request.setValue(new int[] {4}); response = (RemoteAtResponse) xbee.sendSynchronous(request, 10000); if (response.isOk()) { log.info("successfully turned off pin 20 (D0)"); } else { throw new RuntimeException("failed to turn off pin 20. status is " + response.getStatus()); } } catch (XBeeTimeoutException e) { log.error("request timed out. make sure you remote XBee is configured and powered on"); } catch (Exception e) { log.error("unexpected error", e); } finally { xbee.close(); } }
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java index 5b2ba588c..ee808df63 100644 --- a/src/com/android/launcher3/LauncherModel.java +++ b/src/com/android/launcher3/LauncherModel.java @@ -1,3285 +1,3290 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.app.SearchManager; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.*; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.provider.BaseColumns; import android.util.Log; import android.util.Pair; import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; // true = use a "More Apps" folder for non-workspace apps on upgrade // false = strew non-workspace apps across the workspace on upgrade public static final boolean UPGRADE_USE_MORE_APPS_FOLDER = false; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnRemoveableStorage; private final LauncherAppState mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private boolean mIsLoaderTaskRunning; private volatile boolean mFlushingWorkerThread; // Specific runnable types that are run on the main thread deferred handler, this allows us to // clear all queued binding runnables when the Launcher activity is destroyed. private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0; private static final int MAIN_THREAD_BINDING_RUNNABLE = 1; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; // When we are loading pages synchronously, we can't just post the binding of items on the side // pages as this delays the rotation process. Instead, we wait for a callback from the first // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start // a normal load, we also clear this set of Runnables. static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > AllAppsList mBgAllAppsList; // The lock that must be acquired before referencing any static bg data structures. Unlike // other locks, this one can generally be held long-term because we never expect any of these // static data structures to be referenced outside of the worker thread except on the first // load after configuration change. static final Object sBgLock = new Object(); // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>(); // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts // created by LauncherModel that are directly on the home screen (however, no widgets or // shortcuts within folders). static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>(); // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>(); // sBgWorkspaceScreens is the ordered set of workspace screens. static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; protected int mPreviousConfigMcc; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end, boolean forceAnimateIcons); public void bindScreens(ArrayList<Long> orderedScreenIds); public void bindAddScreens(ArrayList<Long> orderedScreenIds); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(boolean upgradePath); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<AppInfo> apps); public void bindAppsAdded(ArrayList<Long> newScreens, ArrayList<ItemInfo> addNotAnimated, ArrayList<ItemInfo> addAnimated, ArrayList<AppInfo> addedApps); public void bindAppsUpdated(ArrayList<AppInfo> apps); public void bindComponentsRemoved(ArrayList<String> packageNames, ArrayList<AppInfo> appInfos, boolean matchPackageNamesOnly); public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts); public void bindSearchablesChanged(); public void onPageBoundSynchronously(int page); public void dumpLogsToLocalData(); } public interface ItemInfoFilter { public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn); } LauncherModel(LauncherAppState app, IconCache iconCache, AppFilter appFilter) { final Context context = app.getContext(); mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable(); mApp = app; mBgAllAppsList = new AllAppsList(iconCache, appFilter); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), context); final Resources res = context.getResources(); Configuration config = res.getConfiguration(); mPreviousConfigMcc = config.mcc; } /** Runs the specified runnable immediately if called from the main thread, otherwise it is * posted on the main thread handler. */ private void runOnMainThread(Runnable r) { runOnMainThread(r, 0); } private void runOnMainThread(Runnable r, int type) { if (sWorkerThread.getThreadId() == Process.myTid()) { // If we are on the worker thread, post onto the main handler mHandler.post(r); } else { r.run(); } } /** Runs the specified runnable immediately if called from the worker thread, otherwise it is * posted on the worker thread handler. */ private static void runOnWorkerThread(Runnable r) { if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { // If we are not on the worker thread, then post to the worker handler sWorker.post(r); } } static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy, long screen) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); final int xCount = (int) grid.numColumns; final int yCount = (int) grid.numRows; boolean[][] occupied = new boolean[xCount][yCount]; int cellX, cellY, spanX, spanY; for (int i = 0; i < items.size(); ++i) { final ItemInfo item = items.get(i); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (item.screenId == screen) { cellX = item.cellX; cellY = item.cellY; spanX = item.spanX; spanY = item.spanY; for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) { for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) { occupied[x][y] = true; } } } } } return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied); } static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name, Intent launchIntent, int firstScreenIndex, ArrayList<Long> workspaceScreens) { // Lock on the app so that we don't try and get the items while apps are being added LauncherAppState app = LauncherAppState.getInstance(); LauncherModel model = app.getModel(); boolean found = false; synchronized (app) { if (sWorkerThread.getThreadId() != Process.myTid()) { // Flush the LauncherModel worker thread, so that if we just did another // processInstallShortcut, we give it time for its shortcut to get added to the // database (getItemsInLocalCoordinates reads the database) model.flushWorkerThread(); } final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context); // Try adding to the workspace screens incrementally, starting at the default or center // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1)) firstScreenIndex = Math.min(firstScreenIndex, workspaceScreens.size()); int count = workspaceScreens.size(); for (int screen = firstScreenIndex; screen < count && !found; screen++) { int[] tmpCoordinates = new int[2]; if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates, workspaceScreens.get(screen))) { // Update the Launcher db return new Pair<Long, int[]>(workspaceScreens.get(screen), tmpCoordinates); } } } return null; } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps, final ArrayList<AppInfo> allAppsApps) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, workspaceApps, cb, allAppsApps); } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> workspaceApps, final Callbacks callbacks, final ArrayList<AppInfo> allAppsApps) { if (workspaceApps.isEmpty() && allAppsApps.isEmpty()) { return; } // Process the newly added applications and add them to the database first Runnable r = new Runnable() { public void run() { final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>(); final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>(); // Get the list of workspace screens. We need to append to this list and // can not use sBgWorkspaceScreens because loadWorkspace() may not have been // called. ArrayList<Long> workspaceScreens = new ArrayList<Long>(); TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(context); for (Integer i : orderedScreens.keySet()) { long screenId = orderedScreens.get(i); workspaceScreens.add(screenId); } synchronized(sBgLock) { Iterator<ItemInfo> iter = workspaceApps.iterator(); while (iter.hasNext()) { ItemInfo a = iter.next(); final String name = a.title.toString(); final Intent launchIntent = a.getIntent(); // Short-circuit this logic if the icon exists somewhere on the workspace if (LauncherModel.shortcutExists(context, name, launchIntent)) { continue; } // Add this icon to the db, creating a new page if necessary. If there // is only the empty page then we just add items to the first page. // Otherwise, we add them to the next pages. int startSearchPageIndex = workspaceScreens.isEmpty() ? 0 : 1; Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex, workspaceScreens); if (coords == null) { LauncherProvider lp = LauncherAppState.getLauncherProvider(); // If we can't find a valid position, then just add a new screen. // This takes time so we need to re-queue the add until the new // page is added. Create as many screens as necessary to satisfy // the startSearchPageIndex. int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 - workspaceScreens.size()); while (numPagesToAdd > 0) { long screenId = lp.generateNewScreenId(); // Save the screen id for binding in the workspace workspaceScreens.add(screenId); addedWorkspaceScreensFinal.add(screenId); numPagesToAdd--; } // Find the coordinate again coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex, workspaceScreens); } if (coords == null) { throw new RuntimeException("Coordinates should not be null"); } ShortcutInfo shortcutInfo; if (a instanceof ShortcutInfo) { shortcutInfo = (ShortcutInfo) a; } else if (a instanceof AppInfo) { shortcutInfo = ((AppInfo) a).makeShortcut(); } else { throw new RuntimeException("Unexpected info type"); } // Add the shortcut to the db addItemToDatabase(context, shortcutInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP, coords.first, coords.second[0], coords.second[1], false); // Save the ShortcutInfo for binding in the workspace addedShortcutsFinal.add(shortcutInfo); } } // Update the workspace screens updateWorkspaceScreenOrder(context, workspaceScreens); if (!addedShortcutsFinal.isEmpty() || !allAppsApps.isEmpty()) { runOnMainThread(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>(); if (!addedShortcutsFinal.isEmpty()) { ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1); long lastScreenId = info.screenId; for (ItemInfo i : addedShortcutsFinal) { if (i.screenId == lastScreenId) { addAnimated.add(i); } else { addNotAnimated.add(i); } } } callbacks.bindAppsAdded(addedWorkspaceScreensFinal, addNotAnimated, addAnimated, allAppsApps); } } }); } } }; runOnWorkerThread(r); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } public void unbindItemInfosAndClearQueuedBindRunnables() { if (sWorkerThread.getThreadId() == Process.myTid()) { throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + "main thread"); } // Clear any deferred bind runnables mDeferredBindRunnables.clear(); // Remove any queued bind runnables mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE); // Unbind all the workspace items unbindWorkspaceItemsOnMainThread(); } /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ void unbindWorkspaceItemsOnMainThread() { // Ensure that we don't use the same workspace items data structure on the main thread // by making a copy of workspace items first. final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>(); synchronized (sBgLock) { tmpWorkspaceItems.addAll(sBgWorkspaceItems); tmpAppWidgets.addAll(sBgAppWidgets); } Runnable r = new Runnable() { @Override public void run() { for (ItemInfo item : tmpWorkspaceItems) { item.unbind(); } for (ItemInfo item : tmpAppWidgets) { item.unbind(); } } }; runOnMainThread(r); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, long screenId, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screenId, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screenId, cellX, cellY); } } static void checkItemInfoLocked( final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem != null && item != modelItem) { // check all the data is consistent if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; ShortcutInfo shortcut = (ShortcutInfo) item; if (modelShortcut.title.toString().equals(shortcut.title.toString()) && modelShortcut.intent.filterEquals(shortcut.intent) && modelShortcut.id == shortcut.id && modelShortcut.itemType == shortcut.itemType && modelShortcut.container == shortcut.container && modelShortcut.screenId == shortcut.screenId && modelShortcut.cellX == shortcut.cellX && modelShortcut.cellY == shortcut.cellY && modelShortcut.spanX == shortcut.spanX && modelShortcut.spanY == shortcut.spanY && ((modelShortcut.dropPos == null && shortcut.dropPos == null) || (modelShortcut.dropPos != null && shortcut.dropPos != null && modelShortcut.dropPos[0] == shortcut.dropPos[0] && modelShortcut.dropPos[1] == shortcut.dropPos[1]))) { // For all intents and purposes, this is the same object return; } } // the modelItem needs to match up perfectly with item if our model is // to be consistent with the database-- for now, just require // modelItem == item or the equality check above String msg = "item: " + ((item != null) ? item.toString() : "null") + "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + "Error: ItemInfo passed to checkItemInfo doesn't match original"; RuntimeException e = new RuntimeException(msg); if (stackTrace != null) { e.setStackTrace(stackTrace); } // TODO: something breaks this in the upgrade path //throw e; } } static void checkItemInfo(final ItemInfo item) { final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); final long itemId = item.id; Runnable r = new Runnable() { public void run() { synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); } } }; runOnWorkerThread(r); } static void updateItemInDatabaseHelper(Context context, final ContentValues values, final ItemInfo item, final String callingFunction) { final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { cr.update(uri, values, null, null); updateItemArrays(item, itemId, stackTrace); } }; runOnWorkerThread(r); } static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, final ArrayList<ItemInfo> items, final String callingFunction) { final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); ContentValues values = valuesList.get(i); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); updateItemArrays(item, itemId, stackTrace); } try { cr.applyBatch(LauncherProvider.AUTHORITY, ops); } catch (Exception e) { e.printStackTrace(); } } }; runOnWorkerThread(r); } static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Item is in a folder, make sure this folder exists if (!sBgFolders.containsKey(item.container)) { // An items container is being set to a that of an item which is not in // the list of Folders. String msg = "item: " + item + " container being set to: " + item.container + ", not in the list of folders"; Log.e(TAG, msg); } } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { switch (modelItem.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: if (!sBgWorkspaceItems.contains(modelItem)) { sBgWorkspaceItems.add(modelItem); } break; default: break; } } else { sBgWorkspaceItems.remove(modelItem); } } } public void flushWorkerThread() { mFlushingWorkerThread = true; Runnable waiter = new Runnable() { public void run() { synchronized (this) { notifyAll(); mFlushingWorkerThread = false; } } }; synchronized(waiter) { runOnWorkerThread(waiter); if (mLoaderTask != null) { synchronized(mLoaderTask) { mLoaderTask.notify(); } } boolean success = false; while (!success) { try { waiter.wait(); success = true; } catch (InterruptedException e) { } } } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); } /** * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the * cellX, cellY have already been updated on the ItemInfos. */ static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, final long container, final int screen) { ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); item.container = container; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, item.cellY); } else { item.screenId = screen; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); contentValues.add(values); } updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); } /** * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> */ static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { item.container = container; item.cellX = cellX; item.cellY = cellY; item.spanX = spanX; item.spanY = spanY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SPANX, item.spanX); values.put(LauncherSettings.Favorites.SPANY, item.spanY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = Math.max(1, c.getInt(spanXIndex)); item.spanY = Math.max(1, c.getInt(spanYIndex)); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.id = LauncherAppState.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Checks whether there is an all apps shortcut in the database */ static boolean hasAllAppsShortcut() { for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { return true; } } return false; } /** * Checks whether there is more than 1 all apps shortcut in the database */ static boolean hasMultipleAllAppsShortcuts() { boolean foundOne = false; for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { if (!foundOne) { foundOne = true; } else { return true; } } } return false; } /** * Add an all apps shortcut to the database if there aren't any already */ private ItemInfo addAllAppsShortcutIfNecessary() { if (hasAllAppsShortcut()) return null; DeviceProfile grid = mApp.getDynamicGrid().getDeviceProfile(); int allAppsIndex = grid.hotseatAllAppsRank; ShortcutInfo allAppsShortcut = new ShortcutInfo(); allAppsShortcut.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; allAppsShortcut.title = mApp.getContext().getResources().getString(R.string.all_apps_button_label); allAppsShortcut.container = ItemInfo.NO_ID; allAppsShortcut.spanX = 1; allAppsShortcut.spanY = 1; LauncherModel.addOrMoveItemInDatabase(mApp.getContext(), allAppsShortcut, LauncherSettings.Favorites.CONTAINER_HOTSEAT, allAppsIndex, allAppsIndex, 0); return allAppsShortcut; } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screensCopy.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screensCopy.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); synchronized (sBgLock) { sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** Loads the workspace screens db into a map of Rank -> ScreenId */ private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) { final ContentResolver contentResolver = context.getContentResolver(); final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true); } } } finally { sc.close(); } return orderedScreens; } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } // check & update map of what's occupied; used to discard overlapping/invalid items public boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item, AtomicBoolean deleteOnItemOverlap) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { - if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { - if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) + if (occupied.containsKey((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { + if (occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " - + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) + + occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0].itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { deleteOnItemOverlap.set(true); } return false; + } else { + ItemInfo[][] hotseatItems = occupied.get( + (long) LauncherSettings.Favorites.CONTAINER_HOTSEAT); + hotseatItems[(int) item.screenId][0] = item; + return true; } } else { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } if (AppsCustomizePagedView.DISABLE_ALL_APPS) { // Ensure that all the applications that are in the system are // represented on the home screen. if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) { verifyApplications(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (AppInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb, null); } } private boolean checkItemDimensions(ItemInfo info) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); return (info.cellX + info.spanX) > (int) grid.numColumns || (info.cellY + info.spanY) > (int) grid.numRows; } /** Clears all the sBg data structures */ private void clearSBgDataStructures() { synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); } } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; // Make sure the default workspace is loaded, if needed LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { clearSBgDataStructures(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int appWidgetProviderIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_PROVIDER); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent = null; while (!mStopped && c.moveToNext()) { AtomicBoolean deleteOnItemOverlap = new AtomicBoolean(false); try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); if (itemType != LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (cn != null && !isValidPackageComponent(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the db Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true); itemsToRemove.add(id); } else { // If apps can be on external storage, then we just // leave them for the user to remove (maybe add // visual treatment to it) Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true); } continue; } } catch (URISyntaxException e) { Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true); continue; } } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else if (itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { info = getShortcutInfo(c, context, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); info.spanX = 1; info.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(info)) { Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: " + info + ", " + grid.numColumns + "x" + grid.numRows, true); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, info, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { throw new RuntimeException("Unexpected null ShortcutInfo"); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); folderInfo.spanX = 1; folderInfo.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(folderInfo)) { Log.d(TAG, "Skipped loading out of bounds folder"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, folderInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); String savedProvider = c.getString(appWidgetProviderIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.addDumpLog(TAG, log, false); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(appWidgetInfo)) { Log.d(TAG, "Skipped loading out of bounds app widget"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, appWidgetInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } String providerName = provider.provider.flattenToString(); if (!providerName.equals(savedProvider)) { ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER, providerName); String where = BaseColumns._ID + "= ?"; String[] args = {Integer.toString(c.getInt(idIndex))}; contentResolver.update(contentUri, values, where, args); } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true); } } } finally { if (c != null) { c.close(); } } // Break early if we've stopped loading if (mStopped) { clearSBgDataStructures(); return false; } // Add an all apps button to the database if there isn't one already ItemInfo allAppsButton = addAllAppsShortcutIfNecessary(); if (allAppsButton != null) { // Check if there was an icon occupying the default position and remove if (occupied.containsKey(allAppsButton.container)) { if (occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0] != null) { itemsToRemove.add(occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0].id); } } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId); } else { TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext); for (Integer i : orderedScreens.keySet()) { sBgWorkspaceScreens.add(orderedScreens.get(i)); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < countY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < countX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { final LauncherAppState app = LauncherAppState.getInstance(); final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = (int) grid.numColumns; int cellCountY = (int) grid.numRows; int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<AppInfo> list = (ArrayList<AppInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos for (int i = 0; i < apps.size(); i++) { ResolveInfo app = apps.get(i); // This builds the icon bitmaps. mBgAllAppsList.add(new AppInfo(packageManager, app, mIconCache, mLabelCache)); } // Huh? Shouldn't this be inside the Runnable below? final ArrayList<AppInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<AppInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<AppInfo> added = null; ArrayList<AppInfo> modified = null; final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<AppInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<AppInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (!AppsCustomizePagedView.DISABLE_ALL_APPS) { addAndBindAddedApps(context, new ArrayList<ItemInfo>(), cb, added); } else { final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); addAndBindAddedApps(context, addedInfos, cb, added); } } if (modified != null) { final ArrayList<AppInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (AppInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } // Remove any queued items from the install queue String spKey = LauncherAppState.getSharedPreferencesKey(); SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE); InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames); } else { for (AppInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); // Write all the logs to disk mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.dumpLogsToLocalData(); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { // Skip if the application is disabled PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0); if (!pi.applicationInfo.enabled) { return false; } // Check the activity return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); final ShortcutInfo info = new ShortcutInfo(); if (componentName != null && !isValidPackageComponent(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } else { try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); info.initFlagsAndFirstInstallTime(pi); } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int titleIndex) { final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; info.title = c.getString(titleIndex); return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<AppInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppInfo> getAppLaunchCountComparator(final Stats stats) { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = stats.launchCount(b.intent) - stats.launchCount(a.intent); if (result == 0) { result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } } return result; } }; } public static final Comparator<AppInfo> getAppInstallTimeComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString().trim(), b.label.toString().trim()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
false
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = Math.max(1, c.getInt(spanXIndex)); item.spanY = Math.max(1, c.getInt(spanYIndex)); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.id = LauncherAppState.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Checks whether there is an all apps shortcut in the database */ static boolean hasAllAppsShortcut() { for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { return true; } } return false; } /** * Checks whether there is more than 1 all apps shortcut in the database */ static boolean hasMultipleAllAppsShortcuts() { boolean foundOne = false; for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { if (!foundOne) { foundOne = true; } else { return true; } } } return false; } /** * Add an all apps shortcut to the database if there aren't any already */ private ItemInfo addAllAppsShortcutIfNecessary() { if (hasAllAppsShortcut()) return null; DeviceProfile grid = mApp.getDynamicGrid().getDeviceProfile(); int allAppsIndex = grid.hotseatAllAppsRank; ShortcutInfo allAppsShortcut = new ShortcutInfo(); allAppsShortcut.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; allAppsShortcut.title = mApp.getContext().getResources().getString(R.string.all_apps_button_label); allAppsShortcut.container = ItemInfo.NO_ID; allAppsShortcut.spanX = 1; allAppsShortcut.spanY = 1; LauncherModel.addOrMoveItemInDatabase(mApp.getContext(), allAppsShortcut, LauncherSettings.Favorites.CONTAINER_HOTSEAT, allAppsIndex, allAppsIndex, 0); return allAppsShortcut; } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screensCopy.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screensCopy.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); synchronized (sBgLock) { sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** Loads the workspace screens db into a map of Rank -> ScreenId */ private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) { final ContentResolver contentResolver = context.getContentResolver(); final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true); } } } finally { sc.close(); } return orderedScreens; } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } // check & update map of what's occupied; used to discard overlapping/invalid items public boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item, AtomicBoolean deleteOnItemOverlap) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0].itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { deleteOnItemOverlap.set(true); } return false; } } else { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } if (AppsCustomizePagedView.DISABLE_ALL_APPS) { // Ensure that all the applications that are in the system are // represented on the home screen. if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) { verifyApplications(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (AppInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb, null); } } private boolean checkItemDimensions(ItemInfo info) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); return (info.cellX + info.spanX) > (int) grid.numColumns || (info.cellY + info.spanY) > (int) grid.numRows; } /** Clears all the sBg data structures */ private void clearSBgDataStructures() { synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); } } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; // Make sure the default workspace is loaded, if needed LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { clearSBgDataStructures(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int appWidgetProviderIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_PROVIDER); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent = null; while (!mStopped && c.moveToNext()) { AtomicBoolean deleteOnItemOverlap = new AtomicBoolean(false); try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); if (itemType != LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (cn != null && !isValidPackageComponent(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the db Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true); itemsToRemove.add(id); } else { // If apps can be on external storage, then we just // leave them for the user to remove (maybe add // visual treatment to it) Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true); } continue; } } catch (URISyntaxException e) { Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true); continue; } } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else if (itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { info = getShortcutInfo(c, context, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); info.spanX = 1; info.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(info)) { Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: " + info + ", " + grid.numColumns + "x" + grid.numRows, true); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, info, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { throw new RuntimeException("Unexpected null ShortcutInfo"); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); folderInfo.spanX = 1; folderInfo.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(folderInfo)) { Log.d(TAG, "Skipped loading out of bounds folder"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, folderInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); String savedProvider = c.getString(appWidgetProviderIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.addDumpLog(TAG, log, false); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(appWidgetInfo)) { Log.d(TAG, "Skipped loading out of bounds app widget"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, appWidgetInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } String providerName = provider.provider.flattenToString(); if (!providerName.equals(savedProvider)) { ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER, providerName); String where = BaseColumns._ID + "= ?"; String[] args = {Integer.toString(c.getInt(idIndex))}; contentResolver.update(contentUri, values, where, args); } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true); } } } finally { if (c != null) { c.close(); } } // Break early if we've stopped loading if (mStopped) { clearSBgDataStructures(); return false; } // Add an all apps button to the database if there isn't one already ItemInfo allAppsButton = addAllAppsShortcutIfNecessary(); if (allAppsButton != null) { // Check if there was an icon occupying the default position and remove if (occupied.containsKey(allAppsButton.container)) { if (occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0] != null) { itemsToRemove.add(occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0].id); } } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId); } else { TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext); for (Integer i : orderedScreens.keySet()) { sBgWorkspaceScreens.add(orderedScreens.get(i)); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < countY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < countX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { final LauncherAppState app = LauncherAppState.getInstance(); final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = (int) grid.numColumns; int cellCountY = (int) grid.numRows; int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<AppInfo> list = (ArrayList<AppInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos for (int i = 0; i < apps.size(); i++) { ResolveInfo app = apps.get(i); // This builds the icon bitmaps. mBgAllAppsList.add(new AppInfo(packageManager, app, mIconCache, mLabelCache)); } // Huh? Shouldn't this be inside the Runnable below? final ArrayList<AppInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<AppInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<AppInfo> added = null; ArrayList<AppInfo> modified = null; final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<AppInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<AppInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (!AppsCustomizePagedView.DISABLE_ALL_APPS) { addAndBindAddedApps(context, new ArrayList<ItemInfo>(), cb, added); } else { final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); addAndBindAddedApps(context, addedInfos, cb, added); } } if (modified != null) { final ArrayList<AppInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (AppInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } // Remove any queued items from the install queue String spKey = LauncherAppState.getSharedPreferencesKey(); SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE); InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames); } else { for (AppInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); // Write all the logs to disk mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.dumpLogsToLocalData(); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { // Skip if the application is disabled PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0); if (!pi.applicationInfo.enabled) { return false; } // Check the activity return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); final ShortcutInfo info = new ShortcutInfo(); if (componentName != null && !isValidPackageComponent(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } else { try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); info.initFlagsAndFirstInstallTime(pi); } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int titleIndex) { final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; info.title = c.getString(titleIndex); return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<AppInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppInfo> getAppLaunchCountComparator(final Stats stats) { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = stats.launchCount(b.intent) - stats.launchCount(a.intent); if (result == 0) { result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } } return result; } }; } public static final Comparator<AppInfo> getAppInstallTimeComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString().trim(), b.label.toString().trim()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = Math.max(1, c.getInt(spanXIndex)); item.spanY = Math.max(1, c.getInt(spanYIndex)); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); item.id = LauncherAppState.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Checks whether there is an all apps shortcut in the database */ static boolean hasAllAppsShortcut() { for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { return true; } } return false; } /** * Checks whether there is more than 1 all apps shortcut in the database */ static boolean hasMultipleAllAppsShortcuts() { boolean foundOne = false; for (ItemInfo info : sBgWorkspaceItems) { if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { if (!foundOne) { foundOne = true; } else { return true; } } } return false; } /** * Add an all apps shortcut to the database if there aren't any already */ private ItemInfo addAllAppsShortcutIfNecessary() { if (hasAllAppsShortcut()) return null; DeviceProfile grid = mApp.getDynamicGrid().getDeviceProfile(); int allAppsIndex = grid.hotseatAllAppsRank; ShortcutInfo allAppsShortcut = new ShortcutInfo(); allAppsShortcut.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; allAppsShortcut.title = mApp.getContext().getResources().getString(R.string.all_apps_button_label); allAppsShortcut.container = ItemInfo.NO_ID; allAppsShortcut.spanX = 1; allAppsShortcut.spanY = 1; LauncherModel.addOrMoveItemInDatabase(mApp.getContext(), allAppsShortcut, LauncherSettings.Favorites.CONTAINER_HOTSEAT, allAppsIndex, allAppsIndex, 0); return allAppsShortcut; } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screensCopy.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screensCopy.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); synchronized (sBgLock) { sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } /** Loads the workspace screens db into a map of Rank -> ScreenId */ private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) { final ContentResolver contentResolver = context.getContentResolver(); final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true); } } } finally { sc.close(); } return orderedScreens; } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } // check & update map of what's occupied; used to discard overlapping/invalid items public boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item, AtomicBoolean deleteOnItemOverlap) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0].itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { deleteOnItemOverlap.set(true); } return false; } else { ItemInfo[][] hotseatItems = occupied.get( (long) LauncherSettings.Favorites.CONTAINER_HOTSEAT); hotseatItems[(int) item.screenId][0] = item; return true; } } else { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[countX + 1][countY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } if (AppsCustomizePagedView.DISABLE_ALL_APPS) { // Ensure that all the applications that are in the system are // represented on the home screen. if (!UPGRADE_USE_MORE_APPS_FOLDER || !isUpgrade) { verifyApplications(); } } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (AppInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb, null); } } private boolean checkItemDimensions(ItemInfo info) { LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); return (info.cellX + info.spanX) > (int) grid.numColumns || (info.cellY + info.spanY) > (int) grid.numRows; } /** Clears all the sBg data structures */ private void clearSBgDataStructures() { synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); } } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); LauncherAppState app = LauncherAppState.getInstance(); DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); int countX = (int) grid.numColumns; int countY = (int) grid.numRows; // Make sure the default workspace is loaded, if needed LauncherAppState.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = LauncherAppState.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { clearSBgDataStructures(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; if (DEBUG_LOADERS) Log.d(TAG, "loading model from " + contentUri); final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int appWidgetProviderIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_PROVIDER); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent = null; while (!mStopped && c.moveToNext()) { AtomicBoolean deleteOnItemOverlap = new AtomicBoolean(false); try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); if (itemType != LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (cn != null && !isValidPackageComponent(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the db Launcher.addDumpLog(TAG, "Invalid package removed: " + cn, true); itemsToRemove.add(id); } else { // If apps can be on external storage, then we just // leave them for the user to remove (maybe add // visual treatment to it) Launcher.addDumpLog(TAG, "Invalid package found: " + cn, true); } continue; } } catch (URISyntaxException e) { Launcher.addDumpLog(TAG, "Invalid uri: " + intentDescription, true); continue; } } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else if (itemType == LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS) { info = getShortcutInfo(c, context, titleIndex); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); info.spanX = 1; info.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(info)) { Launcher.addDumpLog(TAG, "Skipped loading out of bounds shortcut: " + info + ", " + grid.numColumns + "x" + grid.numRows, true); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, info, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { throw new RuntimeException("Unexpected null ShortcutInfo"); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); folderInfo.spanX = 1; folderInfo.spanY = 1; // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(folderInfo)) { Log.d(TAG, "Skipped loading out of bounds folder"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, folderInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); String savedProvider = c.getString(appWidgetProviderIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.addDumpLog(TAG, log, false); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // Skip loading items that are out of bounds if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (checkItemDimensions(appWidgetInfo)) { Log.d(TAG, "Skipped loading out of bounds app widget"); continue; } } // check & update map of what's occupied deleteOnItemOverlap.set(false); if (!checkItemPlacement(occupied, appWidgetInfo, deleteOnItemOverlap)) { if (deleteOnItemOverlap.get()) { itemsToRemove.add(id); } break; } String providerName = provider.provider.flattenToString(); if (!providerName.equals(savedProvider)) { ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER, providerName); String where = BaseColumns._ID + "= ?"; String[] args = {Integer.toString(c.getInt(idIndex))}; contentResolver.update(contentUri, values, where, args); } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Launcher.addDumpLog(TAG, "Desktop items loading interrupted: " + e, true); } } } finally { if (c != null) { c.close(); } } // Break early if we've stopped loading if (mStopped) { clearSBgDataStructures(); return false; } // Add an all apps button to the database if there isn't one already ItemInfo allAppsButton = addAllAppsShortcutIfNecessary(); if (allAppsButton != null) { // Check if there was an icon occupying the default position and remove if (occupied.containsKey(allAppsButton.container)) { if (occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0] != null) { itemsToRemove.add(occupied.get(allAppsButton.container) [(int) allAppsButton.screenId][0].id); } } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); LauncherAppState.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState.getLauncherProvider().updateMaxItemId(maxItemId); } else { TreeMap<Integer, Long> orderedScreens = loadWorkspaceScreensDb(mContext); for (Integer i : orderedScreens.keySet()) { sBgWorkspaceScreens.add(orderedScreens.get(i)); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < countY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < countX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { final LauncherAppState app = LauncherAppState.getInstance(); final DeviceProfile grid = app.getDynamicGrid().getDeviceProfile(); // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = (int) grid.numColumns; int cellCountY = (int) grid.numRows; int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<AppInfo> list = (ArrayList<AppInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos for (int i = 0; i < apps.size(); i++) { ResolveInfo app = apps.get(i); // This builds the icon bitmaps. mBgAllAppsList.add(new AppInfo(packageManager, app, mIconCache, mLabelCache)); } // Huh? Shouldn't this be inside the Runnable below? final ArrayList<AppInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<AppInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removePackageFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<AppInfo> added = null; ArrayList<AppInfo> modified = null; final ArrayList<AppInfo> removedApps = new ArrayList<AppInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<AppInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<AppInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (!AppsCustomizePagedView.DISABLE_ALL_APPS) { addAndBindAddedApps(context, new ArrayList<ItemInfo>(), cb, added); } else { final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); addAndBindAddedApps(context, addedInfos, cb, added); } } if (modified != null) { final ArrayList<AppInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (AppInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } // Remove any queued items from the install queue String spKey = LauncherAppState.getSharedPreferencesKey(); SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE); InstallShortcutReceiver.removeFromInstallQueue(sp, removedPackageNames); } else { for (AppInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); // Write all the logs to disk mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.dumpLogsToLocalData(); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { // Skip if the application is disabled PackageInfo pi = pm.getPackageInfo(cn.getPackageName(), 0); if (!pi.applicationInfo.enabled) { return false; } // Check the activity return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); final ShortcutInfo info = new ShortcutInfo(); if (componentName != null && !isValidPackageComponent(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } else { try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); info.initFlagsAndFirstInstallTime(pi); } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int titleIndex) { final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_ALLAPPS; info.title = c.getString(titleIndex); return info; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<AppInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppInfo> getAppLaunchCountComparator(final Stats stats) { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { int result = stats.launchCount(b.intent) - stats.launchCount(a.intent); if (result == 0) { result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } } return result; } }; } public static final Comparator<AppInfo> getAppInstallTimeComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppInfo>() { public final int compare(AppInfo a, AppInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; int result = collator.compare(a.title.toString().trim(), b.title.toString().trim()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString().trim(), b.label.toString().trim()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString().trim(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString().trim(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); AppInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/squirrel-sql/app/src/net/sourceforge/squirrel_sql/client/mainframe/action/ViewHelpAction.java b/squirrel-sql/app/src/net/sourceforge/squirrel_sql/client/mainframe/action/ViewHelpAction.java index 4e9160868..f503a6805 100644 --- a/squirrel-sql/app/src/net/sourceforge/squirrel_sql/client/mainframe/action/ViewHelpAction.java +++ b/squirrel-sql/app/src/net/sourceforge/squirrel_sql/client/mainframe/action/ViewHelpAction.java @@ -1,79 +1,79 @@ package net.sourceforge.squirrel_sql.client.mainframe.action; /* * Copyright (C) 2002 Colin Bell * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.awt.event.ActionEvent; import java.io.File; import net.sourceforge.squirrel_sql.fw.util.BaseException; import net.sourceforge.squirrel_sql.client.IApplication; import net.sourceforge.squirrel_sql.client.action.SquirrelAction; import net.sourceforge.squirrel_sql.client.util.ApplicationFiles; /** * This <CODE>Action</CODE> displays the Squirrel Help Window. * * @author <A HREF="mailto:[email protected]">Colin Bell</A> */ public class ViewHelpAction extends SquirrelAction { private File _file; /** * Ctor. * * @param app Application API. */ public ViewHelpAction(IApplication app) { this(app, null); } /** * Ctor. * * @param app Application API. * @param file Help file. */ public ViewHelpAction(IApplication app, File file) { super(app); _file = file; app.getResources().setupAction(this); if (_file == null) { _file = new ApplicationFiles().getQuickStartGuideFile(); } } /** * Display the help window. */ public void actionPerformed(ActionEvent evt) { try { new ViewFileCommand(getApplication(), _file).execute(); } catch (BaseException ex) { - getApplication().showErrorDialog("Error viewing change log", ex); + getApplication().showErrorDialog("Error viewing help file", ex); } } }
true
true
public void actionPerformed(ActionEvent evt) { try { new ViewFileCommand(getApplication(), _file).execute(); } catch (BaseException ex) { getApplication().showErrorDialog("Error viewing change log", ex); } }
public void actionPerformed(ActionEvent evt) { try { new ViewFileCommand(getApplication(), _file).execute(); } catch (BaseException ex) { getApplication().showErrorDialog("Error viewing help file", ex); } }
diff --git a/src/me/chaseoes/timingsparser/TimingsFile.java b/src/me/chaseoes/timingsparser/TimingsFile.java index eb1facc..fc09f91 100644 --- a/src/me/chaseoes/timingsparser/TimingsFile.java +++ b/src/me/chaseoes/timingsparser/TimingsFile.java @@ -1,67 +1,67 @@ package me.chaseoes.timingsparser; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class TimingsFile { File file; public TimingsFile(File f) { file = f; } public String parse() throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder pluginTimes = new StringBuilder(); StringBuilder pluginNames = new StringBuilder(); String currentPlugin = null; long totalTime = 0; pluginTimes.append("https://chart.googleapis.com/chart?cht=p3&chd=t:"); while (in.ready()) { String line = in.readLine(); if (line.contains("Total time ")) { totalTime = Long.parseLong(getWord(line, 3)) + totalTime; } } in.close(); in = new BufferedReader(new FileReader(file)); while (in.ready()) { String line = in.readLine(); if (currentPlugin == null) { currentPlugin = getWord(line, 0); } if (line.contains("Total time ")) { int percent = Math.round((float) Long.parseLong(getWord(line, 3)) * 100 / totalTime); if (percent != 0) { + pluginNames.append(currentPlugin); pluginNames.append(" (" + percent + "%)|"); pluginTimes.append(percent + ","); - pluginNames.append(currentPlugin); } currentPlugin = null; } } in.close(); return pluginTimes.toString().substring(0, pluginTimes.toString().length() - 1) + "&chs=750x300&chl=" + pluginNames.toString().substring(0, pluginNames.toString().length() - 1); } public String getWord(String s, int index) { String[] words = s.split("\\s+"); for (int i = 0; i < words.length; i++) { if (i == index) { return words[i]; } } return null; } }
false
true
public String parse() throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder pluginTimes = new StringBuilder(); StringBuilder pluginNames = new StringBuilder(); String currentPlugin = null; long totalTime = 0; pluginTimes.append("https://chart.googleapis.com/chart?cht=p3&chd=t:"); while (in.ready()) { String line = in.readLine(); if (line.contains("Total time ")) { totalTime = Long.parseLong(getWord(line, 3)) + totalTime; } } in.close(); in = new BufferedReader(new FileReader(file)); while (in.ready()) { String line = in.readLine(); if (currentPlugin == null) { currentPlugin = getWord(line, 0); } if (line.contains("Total time ")) { int percent = Math.round((float) Long.parseLong(getWord(line, 3)) * 100 / totalTime); if (percent != 0) { pluginNames.append(" (" + percent + "%)|"); pluginTimes.append(percent + ","); pluginNames.append(currentPlugin); } currentPlugin = null; } } in.close(); return pluginTimes.toString().substring(0, pluginTimes.toString().length() - 1) + "&chs=750x300&chl=" + pluginNames.toString().substring(0, pluginNames.toString().length() - 1); }
public String parse() throws IOException { BufferedReader in = new BufferedReader(new FileReader(file)); StringBuilder pluginTimes = new StringBuilder(); StringBuilder pluginNames = new StringBuilder(); String currentPlugin = null; long totalTime = 0; pluginTimes.append("https://chart.googleapis.com/chart?cht=p3&chd=t:"); while (in.ready()) { String line = in.readLine(); if (line.contains("Total time ")) { totalTime = Long.parseLong(getWord(line, 3)) + totalTime; } } in.close(); in = new BufferedReader(new FileReader(file)); while (in.ready()) { String line = in.readLine(); if (currentPlugin == null) { currentPlugin = getWord(line, 0); } if (line.contains("Total time ")) { int percent = Math.round((float) Long.parseLong(getWord(line, 3)) * 100 / totalTime); if (percent != 0) { pluginNames.append(currentPlugin); pluginNames.append(" (" + percent + "%)|"); pluginTimes.append(percent + ","); } currentPlugin = null; } } in.close(); return pluginTimes.toString().substring(0, pluginTimes.toString().length() - 1) + "&chs=750x300&chl=" + pluginNames.toString().substring(0, pluginNames.toString().length() - 1); }
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/commons/panes/CreateContactInfoPane.java b/OpERP/src/main/java/devopsdistilled/operp/client/commons/panes/CreateContactInfoPane.java index 16548b5e..8a3cab97 100644 --- a/OpERP/src/main/java/devopsdistilled/operp/client/commons/panes/CreateContactInfoPane.java +++ b/OpERP/src/main/java/devopsdistilled/operp/client/commons/panes/CreateContactInfoPane.java @@ -1,109 +1,109 @@ package devopsdistilled.operp.client.commons.panes; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.SubTaskPane; import devopsdistilled.operp.client.commons.panes.controllers.CreateContactInfoPaneController; import devopsdistilled.operp.client.commons.panes.models.observers.CreateContactInfoPaneModelObserver; import devopsdistilled.operp.server.data.entity.commons.PhoneType; public class CreateContactInfoPane extends SubTaskPane implements CreateContactInfoPaneModelObserver { private CreateContactInfoPaneController controller; private final JPanel pane; private final JTextField emailField; private final JTextField workNumField; private final JTextField mobileNumField; private final JTextField homeNumField; public CreateContactInfoPane() { pane = new JPanel(); - pane.setLayout(new MigLayout("", "[grow][grow]", "[][grow][][][][][]")); + pane.setLayout(new MigLayout("", "[][grow]", "[][][][][][][]")); JLabel lblAddress = new JLabel("Address"); pane.add(lblAddress, "flowx,cell 0 0"); JLabel lblEmail = new JLabel("Email"); pane.add(lblEmail, "cell 0 2,alignx trailing"); emailField = new JTextField(); emailField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo() .setEmail(emailField.getText().trim()); } }); pane.add(emailField, "cell 1 2,growx"); emailField.setColumns(10); JLabel lblPhone = new JLabel("Phone"); pane.add(lblPhone, "cell 0 3"); JLabel lblWork = new JLabel("Work"); pane.add(lblWork, "cell 0 4,alignx trailing"); workNumField = new JTextField(); workNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, workNumField.getText().trim()); } }); pane.add(workNumField, "cell 1 4,growx"); workNumField.setColumns(10); JLabel lblMobile = new JLabel("Mobile"); pane.add(lblMobile, "cell 0 5,alignx trailing"); mobileNumField = new JTextField(); mobileNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Mobile, mobileNumField.getText().trim()); } }); pane.add(mobileNumField, "cell 1 5,growx"); mobileNumField.setColumns(10); JLabel lblHome = new JLabel("Home"); pane.add(lblHome, "cell 0 6,alignx trailing"); homeNumField = new JTextField(); homeNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, mobileNumField.getText().trim()); } }); pane.add(homeNumField, "cell 1 6,growx"); homeNumField.setColumns(10); } @Override public JComponent getPane() { return pane; } public void setController(CreateContactInfoPaneController controller) { this.controller = controller; } public void setAddressPanel(JPanel addressPanel) { pane.add(addressPanel, "cell 0 1,grow,span"); pane.validate(); } }
true
true
public CreateContactInfoPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[grow][grow]", "[][grow][][][][][]")); JLabel lblAddress = new JLabel("Address"); pane.add(lblAddress, "flowx,cell 0 0"); JLabel lblEmail = new JLabel("Email"); pane.add(lblEmail, "cell 0 2,alignx trailing"); emailField = new JTextField(); emailField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo() .setEmail(emailField.getText().trim()); } }); pane.add(emailField, "cell 1 2,growx"); emailField.setColumns(10); JLabel lblPhone = new JLabel("Phone"); pane.add(lblPhone, "cell 0 3"); JLabel lblWork = new JLabel("Work"); pane.add(lblWork, "cell 0 4,alignx trailing"); workNumField = new JTextField(); workNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, workNumField.getText().trim()); } }); pane.add(workNumField, "cell 1 4,growx"); workNumField.setColumns(10); JLabel lblMobile = new JLabel("Mobile"); pane.add(lblMobile, "cell 0 5,alignx trailing"); mobileNumField = new JTextField(); mobileNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Mobile, mobileNumField.getText().trim()); } }); pane.add(mobileNumField, "cell 1 5,growx"); mobileNumField.setColumns(10); JLabel lblHome = new JLabel("Home"); pane.add(lblHome, "cell 0 6,alignx trailing"); homeNumField = new JTextField(); homeNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, mobileNumField.getText().trim()); } }); pane.add(homeNumField, "cell 1 6,growx"); homeNumField.setColumns(10); }
public CreateContactInfoPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][grow]", "[][][][][][][]")); JLabel lblAddress = new JLabel("Address"); pane.add(lblAddress, "flowx,cell 0 0"); JLabel lblEmail = new JLabel("Email"); pane.add(lblEmail, "cell 0 2,alignx trailing"); emailField = new JTextField(); emailField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo() .setEmail(emailField.getText().trim()); } }); pane.add(emailField, "cell 1 2,growx"); emailField.setColumns(10); JLabel lblPhone = new JLabel("Phone"); pane.add(lblPhone, "cell 0 3"); JLabel lblWork = new JLabel("Work"); pane.add(lblWork, "cell 0 4,alignx trailing"); workNumField = new JTextField(); workNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, workNumField.getText().trim()); } }); pane.add(workNumField, "cell 1 4,growx"); workNumField.setColumns(10); JLabel lblMobile = new JLabel("Mobile"); pane.add(lblMobile, "cell 0 5,alignx trailing"); mobileNumField = new JTextField(); mobileNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Mobile, mobileNumField.getText().trim()); } }); pane.add(mobileNumField, "cell 1 5,growx"); mobileNumField.setColumns(10); JLabel lblHome = new JLabel("Home"); pane.add(lblHome, "cell 0 6,alignx trailing"); homeNumField = new JTextField(); homeNumField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { controller.getModel().getContactInfo().getPhoneNumbers() .put(PhoneType.Work, mobileNumField.getText().trim()); } }); pane.add(homeNumField, "cell 1 6,growx"); homeNumField.setColumns(10); }
diff --git a/src/main/java/nl/lolmewn/sortal/Localisation.java b/src/main/java/nl/lolmewn/sortal/Localisation.java index d0707b6..7059c4d 100644 --- a/src/main/java/nl/lolmewn/sortal/Localisation.java +++ b/src/main/java/nl/lolmewn/sortal/Localisation.java @@ -1,167 +1,164 @@ package nl.lolmewn.sortal; import java.io.*; import java.util.HashMap; import java.util.logging.Level; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; /** * * @author Lolmewn */ public class Localisation { private File localisation = new File("plugins" + File.separator + "Sortal" + File.separator + "localisation.yml"); private String noPlayer; private String noPerms; private String createNameForgot; private String deleteNameForgot; private String nameInUse; private String warpCreated; private String warpDeleted; private String warpNotFound; private String paymentComplete; private String noMoney; private String noWarpsFound; private String errorInSign; private String playerTeleported; public Localisation() { this.checkFile(); this.loadFile(); } private void checkFile() { if(!this.localisation.exists()){ - try { Bukkit.getLogger().info("[Sortal] Trying to create default language file..."); try { + this.localisation.getParentFile().mkdirs(); InputStream in = this.getClass(). getClassLoader().getResourceAsStream("localisation.yml"); OutputStream out = new BufferedOutputStream( new FileOutputStream(this.localisation)); int c; while ((c = in.read()) != -1) { out.write(c); } out.flush(); out.close(); in.close(); Bukkit.getLogger().info("[Sortal] Default language file created succesfully!"); } catch (Exception e) { e.printStackTrace(); Bukkit.getLogger().warning("[Sortal] Error creating language file! Using default settings!"); } - } catch (Exception e) { - e.printStackTrace(); - } } } private void loadFile() { YamlConfiguration c = YamlConfiguration.loadConfiguration(this.localisation); this.createNameForgot = c.getString("commands.createNameForgotten"); this.deleteNameForgot = c.getString("commands.deleteNameForgotten"); this.nameInUse = c.getString("commands.nameInUse"); this.noMoney = c.getString("noMoney"); this.noPerms = c.getString("noPermissions"); this.paymentComplete = c.getString("paymentComplete"); this.warpCreated = c.getString("commands.warpCreated"); this.warpDeleted = c.getString("commands.warpDeleted"); this.warpNotFound = c.getString("commands.warpNotFound"); this.noWarpsFound = c.getString("commands.noWarpsFound"); this.errorInSign = c.getString("signError"); this.playerTeleported = c.getString("playerTeleported"); Bukkit.getLogger().info("[Sortal] Localisation loaded!"); } public String getCreateNameForgot() { return createNameForgot; } public String getDeleteNameForgot() { return deleteNameForgot; } public String getNameInUse(String warp) { if(this.nameInUse.contains("$WARP") && warp != null && !warp.equals("")){ return nameInUse.replace("$WARP", warp); } return nameInUse; } public String getNoMoney(String money) { if(this.noMoney.contains("$WARP") && money != null && !money.equals("")){ return noMoney.replace("$MONEY", money); } return noMoney; } public String getNoPerms() { return noPerms; } public String getNoPlayer() { return noPlayer; } public String getPaymentComplete(String money) { if(this.paymentComplete.contains("$WARP") && money != null && !money.equals("")){ return paymentComplete.replace("$WARP", money); } return paymentComplete; } public String getWarpCreated(String warp) { if(this.warpCreated.contains("$WARP") && warp != null && !warp.equals("")){ return warpCreated.replace("$WARP", warp); } return warpCreated; } public String getWarpDeleted(String warp) { if(this.warpDeleted.contains("$WARP") && warp != null && !warp.equals("")){ return warpDeleted.replace("$WARP", warp); } return warpDeleted; } public String getWarpNotFound(String warp) { if(this.warpNotFound.contains("$WARP") && warp != null && !warp.equals("")){ return warpNotFound.replace("$WARP", warp); } return warpNotFound; } public String getNoWarpsFound() { return noWarpsFound; } public String getErrorInSign() { return errorInSign; } public String getPlayerTeleported(String dest) { if(this.playerTeleported.contains("$DEST") && dest != null && !dest.equals("")){ return playerTeleported.replace("$DEST", dest); } return playerTeleported; } void addOld(HashMap<String, String> local) { try { YamlConfiguration c = YamlConfiguration.loadConfiguration(this.localisation); for(String path : local.keySet()){ c.set(path, local.get(path)); } c.save(localisation); } catch (IOException ex) { Bukkit.getLogger().log(Level.SEVERE, null, ex); } this.loadFile(); } }
false
true
private void checkFile() { if(!this.localisation.exists()){ try { Bukkit.getLogger().info("[Sortal] Trying to create default language file..."); try { InputStream in = this.getClass(). getClassLoader().getResourceAsStream("localisation.yml"); OutputStream out = new BufferedOutputStream( new FileOutputStream(this.localisation)); int c; while ((c = in.read()) != -1) { out.write(c); } out.flush(); out.close(); in.close(); Bukkit.getLogger().info("[Sortal] Default language file created succesfully!"); } catch (Exception e) { e.printStackTrace(); Bukkit.getLogger().warning("[Sortal] Error creating language file! Using default settings!"); } } catch (Exception e) { e.printStackTrace(); } } }
private void checkFile() { if(!this.localisation.exists()){ Bukkit.getLogger().info("[Sortal] Trying to create default language file..."); try { this.localisation.getParentFile().mkdirs(); InputStream in = this.getClass(). getClassLoader().getResourceAsStream("localisation.yml"); OutputStream out = new BufferedOutputStream( new FileOutputStream(this.localisation)); int c; while ((c = in.read()) != -1) { out.write(c); } out.flush(); out.close(); in.close(); Bukkit.getLogger().info("[Sortal] Default language file created succesfully!"); } catch (Exception e) { e.printStackTrace(); Bukkit.getLogger().warning("[Sortal] Error creating language file! Using default settings!"); } } }
diff --git a/src/gamesincommon/GamesInCommon.java b/src/gamesincommon/GamesInCommon.java index 8cb2a83..fce24f4 100644 --- a/src/gamesincommon/GamesInCommon.java +++ b/src/gamesincommon/GamesInCommon.java @@ -1,325 +1,325 @@ package gamesincommon; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import com.github.koraktor.steamcondenser.exceptions.SteamCondenserException; import com.github.koraktor.steamcondenser.steam.community.SteamGame; import com.github.koraktor.steamcondenser.steam.community.SteamId; public class GamesInCommon { JFrame mainFrame; Connection connection = null; public GamesInCommon() { // initialise database connector connection = InitialDBCheck(); if (connection == null) { throw new RuntimeException("Connection could not be establised to local database."); } // initialise GUI components mainFrame = new JFrame(); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setLocationRelativeTo(null); MainPanel mainPanel = new MainPanel(this); mainFrame.add(mainPanel); mainFrame.pack(); mainFrame.setVisible(true); } /** * Creates local database, if necessary, and creates tables for all enum entries. * * @return A Connection object to the database. */ private Connection InitialDBCheck() { // newDB is TRUE if the database is about to be created by DriverManager.getConnection(); File dbFile = new File("gamedata.db"); boolean newDB = (!(dbFile).exists()); Connection result = null; try { Class.forName("org.sqlite.JDBC"); // attempt to connect to the database result = DriverManager.getConnection("jdbc:sqlite:gamedata.db"); // check all tables from the information schema Statement statement = result.createStatement(); ResultSet resultSet = null; // and copy resultset to List object to enable random access List<String> tableList = new ArrayList<String>(); // skip if new database, as it'll all be new anyway if (!newDB) { // query db resultSet = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); // copy to tableList while (resultSet.next()) { tableList.add(resultSet.getString("name")); } } else { System.out.println("New database created."); } // check all filtertypes have a corresponding table, create if one if not present // skip check and create if the database is new for (FilterType filter : FilterType.values()) { boolean filterFound = false; if (!newDB) { for (String tableName : tableList) { if (tableName.equals(filter.getValue())) { filterFound = true; } } } // if the tableList is traversed and the filter was not found, create a table for it if (!filterFound) { statement.executeUpdate("CREATE TABLE [" + filter.getValue() + "] ( AppID VARCHAR( 16 ) PRIMARY KEY ON CONFLICT FAIL," + "Name VARCHAR( 64 )," + "HasProperty BOOLEAN NOT NULL ON CONFLICT FAIL );"); } } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return result; } /** * Finds common games between an arbitrarily long list of users * * @param users * A list of names to find common games for. * @return A collection of games common to all users */ public Collection<SteamGame> findCommonGames(List<String> users) { List<Collection<SteamGame>> userGames = new ArrayList<Collection<SteamGame>>(); for (String name : users) { try { userGames.add(getGames(SteamId.create(name))); } catch (SteamCondenserException e) { e.printStackTrace(); } } Collection<SteamGame> commonGames = mergeSets(userGames); return commonGames; } /** * Displays all games from a collection on console output * * @param games * The collection to print */ public void displayCommonGames(Collection<SteamGame> games) { // Lists games in common. for (SteamGame i : games) { System.out.println(i.getName()); } // Final count System.out.println("Total games in common: " + games.size()); } /** * Displays all games from a collection in a new graphical interface frame. * * @param games * Games to show. */ public void showCommonGames(Collection<SteamGame> games) { // Create frame object JFrame displayFrame = new JFrame(); displayFrame.setLocationRelativeTo(mainFrame); // Display content JTextArea displayArea = new JTextArea(40, 30); JScrollPane scrollPane = new JScrollPane(displayArea); displayFrame.add(scrollPane); displayArea.setEditable(false); for (SteamGame i : games) { displayArea.append(i.getName() + "\n"); } // Final count displayArea.append("Total games in common: " + games.size()); displayFrame.pack(); displayFrame.setVisible(true); } /** * Creates a list of users from user input. * * @return The list of user names. */ public List<String> getUsers() { List<String> users = new ArrayList<String>(); System.out.println("Enter users one by one, typing 'FIN' when complete:"); try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));) { String input; input = br.readLine(); while (!input.equals("FIN")) { users.add(input); input = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return users; } /** * Finds all games from the given steam user. * * @param sId * The SteamId of the user to get games from. * @return A set of all games for the give user. * @throws SteamCondenserException */ public Collection<SteamGame> getGames(SteamId sId) throws SteamCondenserException { return sId.getGames().values(); } /** * Returns games that match one or more of the given filter types * * @param gameList * Collection of games to be filtered. * @param filterList * Collection of filters to apply. * @return A collection of games matching one or more of filters. */ public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); for (SteamGame game : gameList) { // first run a query through the local db boolean checkWeb = true; try { Statement s = connection.createStatement(); // get list of tables ResultSet tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); // query the table that matches the filter while (tableSet.next()) { for (FilterType filter : filterList) { // WARNING - This does NOT trigger a webpage update if one or more filters have no DB data, but at least one filter // is TRUE ResultSet rSet = null; if (filter.getValue().equals((tableSet.getString("name")))) { rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match while ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty") && (!result.contains(game))) { result.add(game); } // if there's an entry in the database, no need to check anywhere else checkWeb = false; System.out.println("[SQL] Checked game '" + game.getName() + "'"); } } } } catch (SQLException e1) { e1.printStackTrace(); } // if checkWeb never got turned to false, we need to fetch data from the steampowered.com website if (checkWeb) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); - if (line.contains(filter.getValue())) { + if (line.contains("\"" + filter.getValue() + "\"")) { result.add(game); // success - add to db connection.createStatement().executeUpdate( "INSERT INTO [" + filter.getValue() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 1)"); foundProperties.put(filter, true); } } } // insert filters returning false as false to the DB for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { if (entry.getValue().equals(new Boolean(false))) { connection.createStatement().executeUpdate( "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 0)"); } } System.out.println("[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e) { e.printStackTrace(); } } } return result; } /** * Merges multiple user game sets together to keep all games that are the same. * * @param userGames * A list of user game sets. There must be at least one set in this list. * @return A set containing all common games. */ public Collection<SteamGame> mergeSets(List<Collection<SteamGame>> userGames) { Collection<SteamGame> result = userGames.get(0); for (int i = 1; i < userGames.size(); i++) { result.retainAll(userGames.get(i)); } return result; } public String sanitiseInputString(String input) { return input.replace("'", "''"); } public static void main(String[] args) { GamesInCommon gamesInCommon = new GamesInCommon(); // List<String> users = gamesInCommon.getUsers(); // gamesInCommon.displayCommonGames(gamesInCommon.findCommonGames(users)); } }
true
true
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); for (SteamGame game : gameList) { // first run a query through the local db boolean checkWeb = true; try { Statement s = connection.createStatement(); // get list of tables ResultSet tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); // query the table that matches the filter while (tableSet.next()) { for (FilterType filter : filterList) { // WARNING - This does NOT trigger a webpage update if one or more filters have no DB data, but at least one filter // is TRUE ResultSet rSet = null; if (filter.getValue().equals((tableSet.getString("name")))) { rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match while ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty") && (!result.contains(game))) { result.add(game); } // if there's an entry in the database, no need to check anywhere else checkWeb = false; System.out.println("[SQL] Checked game '" + game.getName() + "'"); } } } } catch (SQLException e1) { e1.printStackTrace(); } // if checkWeb never got turned to false, we need to fetch data from the steampowered.com website if (checkWeb) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); if (line.contains(filter.getValue())) { result.add(game); // success - add to db connection.createStatement().executeUpdate( "INSERT INTO [" + filter.getValue() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 1)"); foundProperties.put(filter, true); } } } // insert filters returning false as false to the DB for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { if (entry.getValue().equals(new Boolean(false))) { connection.createStatement().executeUpdate( "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 0)"); } } System.out.println("[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e) { e.printStackTrace(); } } } return result; }
public Collection<SteamGame> filterGames(Collection<SteamGame> gameList, List<FilterType> filterList) { Collection<SteamGame> result = new HashSet<SteamGame>(); for (SteamGame game : gameList) { // first run a query through the local db boolean checkWeb = true; try { Statement s = connection.createStatement(); // get list of tables ResultSet tableSet = s.executeQuery("SELECT name FROM sqlite_master WHERE type='table';"); // query the table that matches the filter while (tableSet.next()) { for (FilterType filter : filterList) { // WARNING - This does NOT trigger a webpage update if one or more filters have no DB data, but at least one filter // is TRUE ResultSet rSet = null; if (filter.getValue().equals((tableSet.getString("name")))) { rSet = s.executeQuery("SELECT * FROM [" + tableSet.getString("name") + "] WHERE AppID = '" + game.getAppId() + "'"); } // if rSet.next() indicates a match while ((rSet != null) && (rSet.next())) { // if the game passes the filter and is not already in the result collection, add it if (rSet.getBoolean("HasProperty") && (!result.contains(game))) { result.add(game); } // if there's an entry in the database, no need to check anywhere else checkWeb = false; System.out.println("[SQL] Checked game '" + game.getName() + "'"); } } } } catch (SQLException e1) { e1.printStackTrace(); } // if checkWeb never got turned to false, we need to fetch data from the steampowered.com website if (checkWeb) { // foundProperties records whether it has or does not have each of the filters HashMap<FilterType, Boolean> foundProperties = new HashMap<FilterType, Boolean>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL( "http://store.steampowered.com/api/appdetails/?appids=" + game.getAppId()).openStream()));) { // Read lines in until there are no more to be read, run filter on each line looking for specified package IDs. String line; while (((line = br.readLine()) != null) && (!result.contains(game))) { for (FilterType filter : filterList) { // default false until set to true foundProperties.put(filter, false); if (line.contains("\"" + filter.getValue() + "\"")) { result.add(game); // success - add to db connection.createStatement().executeUpdate( "INSERT INTO [" + filter.getValue() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 1)"); foundProperties.put(filter, true); } } } // insert filters returning false as false to the DB for (Map.Entry<FilterType, Boolean> entry : foundProperties.entrySet()) { if (entry.getValue().equals(new Boolean(false))) { connection.createStatement().executeUpdate( "INSERT INTO [" + entry.getKey().toString() + "] (AppID, Name, HasProperty) VALUES ('" + game.getAppId() + "','" + sanitiseInputString(game.getName()) + "', 0)"); } } System.out.println("[WEB] Checked game '" + game.getName() + "'"); } catch (IOException | SQLException e) { e.printStackTrace(); } } } return result; }
diff --git a/ring/ReductionPar.java b/ring/ReductionPar.java index b2e529e6..e21a3183 100644 --- a/ring/ReductionPar.java +++ b/ring/ReductionPar.java @@ -1,227 +1,228 @@ /* * $Id$ */ package edu.jas.ring; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Iterator; import java.util.Collection; import java.util.Map; import org.apache.log4j.Logger; import edu.jas.structure.RingElem; import edu.jas.poly.ExpVector; import edu.jas.poly.GenPolynomial; import edu.jas.poly.GenSolvablePolynomial; import edu.jas.util.DistHashTable; /** * Polynomial Reduction parallel class. * Implements normalform. * @author Heinz Kredel */ public class ReductionPar<C extends RingElem<C>> extends ReductionAbstract<C> { private static Logger logger = Logger.getLogger(ReductionPar.class); /** * Constructor. */ public ReductionPar() { } /** * Normalform. Allows concurrent modification of the list. * @param C coefficient type. * @param Ap polynomial. * @param Pp polynomial list, concurrent modification allowed. * @return nf(Ap) with respect to Pp. */ public GenPolynomial<C> normalform(List<GenPolynomial<C>> Pp, GenPolynomial<C> Ap) { if ( Pp == null ) return Ap; if ( Pp.isEmpty() ) return Ap; int l; GenPolynomial<C>[] P; synchronized (Pp) { // required, ok in dist l = Pp.size(); P = new GenPolynomial[l]; //P = Pp.values().toArray(); for ( int i = 0; i < Pp.size(); i++ ) { P[i] = Pp.get(i); } } Map.Entry<ExpVector,C> m; Map.Entry<ExpVector,C> m1; ExpVector e; ExpVector f = null; C a; boolean mt = false; GenPolynomial<C> Rz = Ap.ring.getZERO(); GenPolynomial<C> R = Rz; GenPolynomial<C> p = null; GenPolynomial<C> Q = null; GenPolynomial<C> S = Ap; while ( S.length() > 0 ) { if ( Pp.size() != l ) { //long t = System.currentTimeMillis(); synchronized (Pp) { // required, bad in parallel l = Pp.size(); P = new GenPolynomial[ l ]; //P = Pp.toArray(); for ( int i = 0; i < Pp.size(); i++ ) { P[i] = Pp.get(i); } } //t = System.currentTimeMillis()-t; //logger.info("Pp.toArray() = " + t + " ms, size() = " + l); S = Ap; // S.add(R)? // restart reduction ? R = Rz; } m = S.leadingMonomial(); e = m.getKey(); a = m.getValue(); for ( int i = 0; i < P.length ; i++ ) { p = P[i]; f = p.leadingExpVector(); if ( f != null ) { mt = ExpVector.EVMT( e, f ); if ( mt ) break; } } if ( ! mt ) { //logger.debug("irred"); //T = new OrderedMapPolynomial( a, e ); R = R.add( a, e ); S = S.subtract( a, e ); // System.out.println(" S = " + S); } else { //logger.debug("red"); m1 = p.leadingMonomial(); e = ExpVector.EVDIF( e, f ); a = a.divide( m1.getValue() ); Q = p.multiply( a, e ); S = S.subtract( Q ); } } return R; } /** * Normalform with recording. * @param C coefficient type. * @param row recording matrix, is modified. * @param Pp a polynomial list for reduction. * @param Ap a polynomial. * @return nf(Pp,Ap), the normal form of Ap wrt. Pp. */ public GenPolynomial<C> normalform(List<GenPolynomial<C>> row, List<GenPolynomial<C>> Pp, GenPolynomial<C> Ap) { throw new RuntimeException("normalform with recording not implemented"); } /** * Normalform. Allows concurrent modification of the DHT. * @param C coefficient type. * @param Ap polynomial. * @param Pp distributed hash table, concurrent modification allowed. * @return nf(Ap) with respect to Pp. */ public GenPolynomial<C> normalform(DistHashTable Pp, GenPolynomial<C> Ap) { if ( Pp == null ) return Ap; if ( Pp.isEmpty() ) return Ap; int l; GenPolynomial<C>[] P; - synchronized (Pp) { // required, ok in dist + synchronized ( Pp.getList() ) { // required, ok in dist l = Pp.size(); P = new GenPolynomial[l]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } Map.Entry<ExpVector,C> m; Map.Entry<ExpVector,C> m1; ExpVector e; ExpVector f = null; C a; boolean mt = false; GenPolynomial<C> Rz = Ap.ring.getZERO(); GenPolynomial<C> R = Rz; GenPolynomial<C> p = null; GenPolynomial<C> Q = null; GenPolynomial<C> S = Ap; while ( S.length() > 0 ) { if ( Pp.size() != l ) { //long t = System.currentTimeMillis(); - synchronized (Pp) { // required, ok in distributed + synchronized ( Pp.getList() ) { // required, ok in distributed l = Pp.size(); P = new GenPolynomial[ l ]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } //t = System.currentTimeMillis()-t; //logger.info("Pp.toArray() = " + t + " ms, size() = " + l); + //logger.info("Pp.toArray() size() = " + l); S = Ap; // S.add(R)? // restart reduction ? R = Rz; } m = S.leadingMonomial(); e = m.getKey(); a = m.getValue(); for ( int i = 0; i < P.length ; i++ ) { p = P[i]; f = p.leadingExpVector(); if ( f != null ) { mt = ExpVector.EVMT( e, f ); if ( mt ) break; } } if ( ! mt ) { //logger.debug("irred"); //T = new OrderedMapPolynomial( a, e ); R = R.add( a, e ); S = S.subtract( a, e ); // System.out.println(" S = " + S); } else { //logger.debug("red"); m1 = p.leadingMonomial(); e = ExpVector.EVDIF( e, f ); a = a.divide( m1.getValue() ); Q = p.multiply( a, e ); S = S.subtract( Q ); } } return R; } }
false
true
public GenPolynomial<C> normalform(DistHashTable Pp, GenPolynomial<C> Ap) { if ( Pp == null ) return Ap; if ( Pp.isEmpty() ) return Ap; int l; GenPolynomial<C>[] P; synchronized (Pp) { // required, ok in dist l = Pp.size(); P = new GenPolynomial[l]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } Map.Entry<ExpVector,C> m; Map.Entry<ExpVector,C> m1; ExpVector e; ExpVector f = null; C a; boolean mt = false; GenPolynomial<C> Rz = Ap.ring.getZERO(); GenPolynomial<C> R = Rz; GenPolynomial<C> p = null; GenPolynomial<C> Q = null; GenPolynomial<C> S = Ap; while ( S.length() > 0 ) { if ( Pp.size() != l ) { //long t = System.currentTimeMillis(); synchronized (Pp) { // required, ok in distributed l = Pp.size(); P = new GenPolynomial[ l ]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } //t = System.currentTimeMillis()-t; //logger.info("Pp.toArray() = " + t + " ms, size() = " + l); S = Ap; // S.add(R)? // restart reduction ? R = Rz; } m = S.leadingMonomial(); e = m.getKey(); a = m.getValue(); for ( int i = 0; i < P.length ; i++ ) { p = P[i]; f = p.leadingExpVector(); if ( f != null ) { mt = ExpVector.EVMT( e, f ); if ( mt ) break; } } if ( ! mt ) { //logger.debug("irred"); //T = new OrderedMapPolynomial( a, e ); R = R.add( a, e ); S = S.subtract( a, e ); // System.out.println(" S = " + S); } else { //logger.debug("red"); m1 = p.leadingMonomial(); e = ExpVector.EVDIF( e, f ); a = a.divide( m1.getValue() ); Q = p.multiply( a, e ); S = S.subtract( Q ); } } return R; }
public GenPolynomial<C> normalform(DistHashTable Pp, GenPolynomial<C> Ap) { if ( Pp == null ) return Ap; if ( Pp.isEmpty() ) return Ap; int l; GenPolynomial<C>[] P; synchronized ( Pp.getList() ) { // required, ok in dist l = Pp.size(); P = new GenPolynomial[l]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } Map.Entry<ExpVector,C> m; Map.Entry<ExpVector,C> m1; ExpVector e; ExpVector f = null; C a; boolean mt = false; GenPolynomial<C> Rz = Ap.ring.getZERO(); GenPolynomial<C> R = Rz; GenPolynomial<C> p = null; GenPolynomial<C> Q = null; GenPolynomial<C> S = Ap; while ( S.length() > 0 ) { if ( Pp.size() != l ) { //long t = System.currentTimeMillis(); synchronized ( Pp.getList() ) { // required, ok in distributed l = Pp.size(); P = new GenPolynomial[ l ]; //P = Pp.values().toArray(); Collection<GenPolynomial<C>> Pv = (Collection<GenPolynomial<C>>)Pp.values(); int i = 0; for ( GenPolynomial<C> x : Pv ) { P[i++] = x; } } //t = System.currentTimeMillis()-t; //logger.info("Pp.toArray() = " + t + " ms, size() = " + l); //logger.info("Pp.toArray() size() = " + l); S = Ap; // S.add(R)? // restart reduction ? R = Rz; } m = S.leadingMonomial(); e = m.getKey(); a = m.getValue(); for ( int i = 0; i < P.length ; i++ ) { p = P[i]; f = p.leadingExpVector(); if ( f != null ) { mt = ExpVector.EVMT( e, f ); if ( mt ) break; } } if ( ! mt ) { //logger.debug("irred"); //T = new OrderedMapPolynomial( a, e ); R = R.add( a, e ); S = S.subtract( a, e ); // System.out.println(" S = " + S); } else { //logger.debug("red"); m1 = p.leadingMonomial(); e = ExpVector.EVDIF( e, f ); a = a.divide( m1.getValue() ); Q = p.multiply( a, e ); S = S.subtract( Q ); } } return R; }
diff --git a/srcj/com/sun/electric/technology/technologies/MoCMOS.java b/srcj/com/sun/electric/technology/technologies/MoCMOS.java index 129b3b43a..cd3069dd7 100755 --- a/srcj/com/sun/electric/technology/technologies/MoCMOS.java +++ b/srcj/com/sun/electric/technology/technologies/MoCMOS.java @@ -1,4536 +1,4536 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: MoCMOS.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.technology.technologies; import com.sun.electric.Main; import com.sun.electric.database.geometry.EGraphics; import com.sun.electric.database.geometry.Poly; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.prototype.NodeProto; import com.sun.electric.database.prototype.PortCharacteristic; import com.sun.electric.database.text.Pref; import com.sun.electric.database.text.TextUtils; import com.sun.electric.database.topology.NodeInst; import com.sun.electric.database.topology.ArcInst; import com.sun.electric.database.topology.Connection; import com.sun.electric.database.variable.ElectricObject; import com.sun.electric.database.variable.VarContext; import com.sun.electric.database.variable.Variable; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.technology.Technology.TechPoint; import com.sun.electric.technology.technologies.utils.MOSRules; import com.sun.electric.technology.*; import com.sun.electric.tool.user.ui.EditWindow; import java.awt.Color; import java.awt.geom.Rectangle2D; import java.util.Iterator; import java.util.List; import java.util.ArrayList; /** * This is the MOSIS CMOS technology. */ public class MoCMOS extends Technology { /** the MOSIS CMOS Technology object. */ public static final MoCMOS tech = new MoCMOS(); /** Value for standard SCMOS rules. */ public static final int SCMOSRULES = 0; /** Value for submicron rules. */ public static final int SUBMRULES = 1; /** Value for deep rules. */ public static final int DEEPRULES = 2; /** key of Variable for saving technology state. */ public static final Variable.Key TECH_LAST_STATE = ElectricObject.newKey("TECH_last_state"); /** key of Variable for saving scalable transistor contact information. */ public static final Variable.Key TRANS_CONTACT = ElectricObject.newKey("MOCMOS_transcontacts"); // layers private Layer poly1_lay, transistorPoly_lay; // arcs /** metal 1->6 arc */ private ArcProto[] metalArcs = new ArcProto[6]; /** polysilicon 1 arc */ private ArcProto poly1_arc; /** polysilicon 2 arc */ private ArcProto poly2_arc; /** P/N-active arc */ ArcProto[] activeArcs = new ArcProto[2]; /** General active arc */ private ArcProto active_arc; // nodes /** metal-1->6-pin */ private PrimitiveNode[] metalPinNodes = new PrimitiveNode[6]; /** polysilicon-1-pin */ private PrimitiveNode poly1Pin_node; /** polysilicon-2-pin */ private PrimitiveNode poly2Pin_node; /** P/N-active-pins */ private PrimitiveNode[] activePinNodes = new PrimitiveNode[2]; /** General active-pin */ private PrimitiveNode activePin_node; /** metal-1-P/N-active-contacts */ private PrimitiveNode[] metalActiveContactNodes = new PrimitiveNode[2]; /** metal-1-polysilicon-1-contact */ private PrimitiveNode metal1Poly1Contact_node; /** metal-1-polysilicon-2-contact */ private PrimitiveNode metal1Poly2Contact_node; /** metal-1-polysilicon-1-2-contact */ private PrimitiveNode metal1Poly12Contact_node; /** P/N-Transistors */ private PrimitiveNode[] transistorNodes = new PrimitiveNode[2]; /** ThickOxide Transistors */ private PrimitiveNode[] thickTransistorNodes = new PrimitiveNode[2]; /** Scalable Transistors */ private PrimitiveNode[] scalableTransistorNodes = new PrimitiveNode[2]; /** M1M2 -> M5M6 contacts */ private PrimitiveNode[] metalContactNodes = new PrimitiveNode[5]; /** metal-1-P/N-Well-contacts */ private PrimitiveNode[] metalWellContactNodes = new PrimitiveNode[2]; /** RPO poly resistors */ private PrimitiveNode[] rpoResistorNodes = new PrimitiveNode[2]; /** Metal-1-Node */ private PrimitiveNode metal1Node_node; /** Metal-2-Node */ private PrimitiveNode metal2Node_node; /** Metal-3-Node */ private PrimitiveNode metal3Node_node; /** Metal-4-Node */ private PrimitiveNode metal4Node_node; /** Metal-5-Node */ private PrimitiveNode metal5Node_node; /** Metal-6-Node */ private PrimitiveNode metal6Node_node; /** Polysilicon-1-Node */ private PrimitiveNode poly1Node_node; /** Polysilicon-2-Node */ private PrimitiveNode poly2Node_node; /** P-Active-Node */ private PrimitiveNode pActiveNode_node; /** N-Active-Node */ private PrimitiveNode nActiveNode_node; /** P-Select-Node */ private PrimitiveNode pSelectNode_node; /** N-Select-Node */ private PrimitiveNode nSelectNode_node; /** PolyCut-Node */ private PrimitiveNode polyCutNode_node; /** ActiveCut-Node */ private PrimitiveNode activeCutNode_node; /** Via-1-Node */ private PrimitiveNode via1Node_node; /** Via-2-Node */ private PrimitiveNode via2Node_node; /** Via-3-Node */ private PrimitiveNode via3Node_node; /** Via-4-Node */ private PrimitiveNode via4Node_node; /** Via-5-Node */ private PrimitiveNode via5Node_node; /** P-Well-Node */ private PrimitiveNode pWellNode_node; /** N-Well-Node */ private PrimitiveNode nWellNode_node; /** Passivation-Node */ private PrimitiveNode passivationNode_node; /** Pad-Frame-Node */ private PrimitiveNode padFrameNode_node; /** Poly-Cap-Node */ private PrimitiveNode polyCapNode_node; /** P-Active-Well-Node */ private PrimitiveNode pActiveWellNode_node; /** Polysilicon-1-Transistor-Node */ private PrimitiveNode polyTransistorNode_node; /** Silicide-Block-Node */ private PrimitiveNode silicideBlockNode_node; /** Thick-Active-Node */ private PrimitiveNode thickActiveNode_node; // for dynamically modifying the transistor geometry private Technology.NodeLayer[] transistorPolyLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorActiveLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorActiveTLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorActiveBLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorPolyLLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorPolyRLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorPolyCLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorWellLayers = new Technology.NodeLayer[2]; private Technology.NodeLayer[] transistorSelectLayers = new Technology.NodeLayer[2]; // design rule constants /** wide rules apply to geometry larger than this */ private static final double WIDELIMIT = 100; private DRCTemplate [] theRules = new DRCTemplate[] { new DRCTemplate("1.1", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.MINWID, "P-Well", null, 12, null), new DRCTemplate("1.1", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.MINWID, "N-Well", null, 12, null), new DRCTemplate("1.1", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.MINWID, "Pseudo-P-Well", null, 12, null), new DRCTemplate("1.1", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.MINWID, "Pseudo-N-Well", null, 12, null), new DRCTemplate("1.1", DRCTemplate.SC, DRCTemplate.MINWID, "P-Well", null, 10, null), new DRCTemplate("1.1", DRCTemplate.SC, DRCTemplate.MINWID, "N-Well", null, 10, null), new DRCTemplate("1.1", DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-P-Well", null, 10, null), new DRCTemplate("1.1", DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-N-Well", null, 10, null), new DRCTemplate("1.2", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.UCONSPA, "P-Well", "P-Well", 18, null), new DRCTemplate("1.2", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.UCONSPA, "N-Well", "N-Well", 18, null), new DRCTemplate("1.2", DRCTemplate.SC, DRCTemplate.UCONSPA, "P-Well", "P-Well", 9, null), new DRCTemplate("1.2", DRCTemplate.SC, DRCTemplate.UCONSPA, "N-Well", "N-Well", 9, null), new DRCTemplate("1.3", DRCTemplate.ALL, DRCTemplate.CONSPA, "P-Well", "P-Well", 6, null), new DRCTemplate("1.3", DRCTemplate.ALL, DRCTemplate.CONSPA, "N-Well", "N-Well", 6, null), // Valid in case of unconnected node or connected node UCONSPA -> SPACING May 21, 05 new DRCTemplate("1.4", DRCTemplate.ALL, DRCTemplate.SPACING, "P-Well", "N-Well", 0, null), new DRCTemplate("2.1", DRCTemplate.ALL, DRCTemplate.MINWID, "P-Active", null, 3, null), new DRCTemplate("2.1", DRCTemplate.ALL, DRCTemplate.MINWID, "N-Active", null, 3, null), new DRCTemplate("2.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "P-Active", "P-Active", 3, null), new DRCTemplate("2.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "N-Active", "N-Active", 3, null), new DRCTemplate("2.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "P-Active-Well", "P-Active-Well", 3, null), new DRCTemplate("2.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "P-Active", "P-Active-Well", 3, null), new DRCTemplate("2.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "N-Active", "P-Active-Well", 3, null), new DRCTemplate("2.2 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "P-Active", "P-Active", 2.8, null), new DRCTemplate("2.2 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "N-Active", "N-Active", 2.8, null), new DRCTemplate("2.2 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "P-Active-Well", "P-Active-Well", 2.8, null), new DRCTemplate("2.2 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "P-Active", "P-Active-Well", 2.8, null), new DRCTemplate("2.2 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "N-Active", "P-Active-Well", 2.8, null), new DRCTemplate("2.3", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SURROUND, "N-Well", "P-Active", 6, "Metal-1-P-Active-Con"), new DRCTemplate("2.3", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.ASURROUND,"N-Well", "P-Active", 6, "P-Active"), new DRCTemplate("2.3", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SURROUND, "P-Well", "N-Active", 6, "Metal-1-N-Active-Con"), new DRCTemplate("2.3", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.ASURROUND,"P-Well", "N-Active", 6, "N-Active"), new DRCTemplate("2.3", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.TRAWELL, null, null, 6, null), new DRCTemplate("2.3", DRCTemplate.SC, DRCTemplate.SURROUND, "N-Well", "P-Active", 5, "Metal-1-P-Active-Con"), new DRCTemplate("2.3", DRCTemplate.SC, DRCTemplate.ASURROUND,"N-Well", "P-Active", 5, "P-Active"), new DRCTemplate("2.3", DRCTemplate.SC, DRCTemplate.SURROUND, "P-Well", "N-Active", 5, "Metal-1-N-Active-Con"), new DRCTemplate("2.3", DRCTemplate.SC, DRCTemplate.ASURROUND,"P-Well", "N-Active", 5, "N-Active"), new DRCTemplate("2.3", DRCTemplate.SC, DRCTemplate.TRAWELL, null, null, 5, null), // Rule 2.4 not implemented // In C-Electric it is implemented as 2.2 (min spacing=3) so we might discrepancies. new DRCTemplate("2.5 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "P-Active", "N-Active", 4, null), new DRCTemplate("2.5 TSMC (OD.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "P-Active", "N-Active", 2.8, null), new DRCTemplate("3.1 Mosis", DRCTemplate.MOSIS, DRCTemplate.MINWID, "Polysilicon-1", null, 2, null), new DRCTemplate("3.1 TSMC", DRCTemplate.TSMC, DRCTemplate.MINWID, "Polysilicon-1", null, 1.8, null), new DRCTemplate("3.1 Mosis", DRCTemplate.MOSIS, DRCTemplate.MINWID, "Transistor-Poly", null, 2, null), new DRCTemplate("3.1 TSMC", DRCTemplate.TSMC, DRCTemplate.MINWID, "Transistor-Poly", null, 1.8, null), new DRCTemplate("3.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Polysilicon-1", "Polysilicon-1", 3, null), new DRCTemplate("3.2 TSMC (PO.S.2/PO.S.3)", DRCTemplate.TSMC|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Polysilicon-1", "Polysilicon-1", 2.5, null), new DRCTemplate("3.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Polysilicon-1", "Transistor-Poly",3, null), new DRCTemplate("3.2 TSMC (PO.S.2/PO.S.3)", DRCTemplate.TSMC|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Polysilicon-1", "Transistor-Poly",2.5, null), new DRCTemplate("3.2", DRCTemplate.SC, DRCTemplate.SPACING, "Polysilicon-1", "Polysilicon-1", 2, null), new DRCTemplate("3.2", DRCTemplate.SC, DRCTemplate.SPACING, "Polysilicon-1", "Transistor-Poly",2, null), new DRCTemplate("3.2a", DRCTemplate.DE, DRCTemplate.SPACING, "Transistor-Poly","Transistor-Poly",4, null), new DRCTemplate("3.2a", DRCTemplate.SU, DRCTemplate.SPACING, "Transistor-Poly","Transistor-Poly",3, null), new DRCTemplate("3.2a", DRCTemplate.SC, DRCTemplate.SPACING, "Transistor-Poly","Transistor-Poly",2, null), new DRCTemplate("3.3", DRCTemplate.DE, DRCTemplate.TRAPOLY, null, null, 2.5,null), new DRCTemplate("3.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.TRAPOLY, null, null, 2, null), new DRCTemplate("3.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.TRAPOLY, null, null, 2.2, null), new DRCTemplate("3.4", DRCTemplate.DE, DRCTemplate.TRAACTIVE, null, null, 4, null), new DRCTemplate("3.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.TRAACTIVE, null, null, 3, null), // new DRCTemplate("3.4 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.TRAACTIVE, null, null, 3.2, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Polysilicon-1", "P-Active", 1, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Transistor-Poly","P-Active", 1, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Polysilicon-1", "N-Active", 1, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Transistor-Poly","N-Active", 1, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Polysilicon-1", "P-Active-Well", 1, null), new DRCTemplate("3.5", DRCTemplate.ALL, DRCTemplate.SPACING, "Transistor-Poly","P-Active-Well", 1, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.MINWID, "P-Select", null, 4, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.MINWID, "N-Select", null, 4, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.MINWID, "Pseudo-P-Select", null, 4, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.MINWID, "Pseudo-N-Select", null, 4, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.SPACING, "P-Select", "P-Select", 4, null), new DRCTemplate("4.4", DRCTemplate.DE, DRCTemplate.SPACING, "N-Select", "N-Select", 4, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "P-Select", null, 2, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "N-Select", null, 2, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-P-Select", null, 2, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-N-Select", null, 2, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "P-Select", "P-Select", 2, null), new DRCTemplate("4.4 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "N-Select", "N-Select", 2, null), new DRCTemplate("4.4 TSMC (PP/NP.W.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "P-Select", null, 4.4, null), new DRCTemplate("4.4 TSMC (PP/NP.W.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "N-Select", null, 4.4, null), new DRCTemplate("4.4 TSMC (PP/NP.W.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-P-Select", null, 4.4, null), new DRCTemplate("4.4 TSMC (PP/NP.W.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Pseudo-N-Select", null, 4.4, null), new DRCTemplate("4.4 TSMC (N/PP.S.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "P-Select", "P-Select", 4.4, null), new DRCTemplate("4.4 TSMC (N/PP.S.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "N-Select", "N-Select", 4.4, null), new DRCTemplate("4.4", DRCTemplate.ALL, DRCTemplate.SPACING, "P-Select", "N-Select", 0, null), // new DRCTemplate("PP/NP.C.1 4", DRCTemplate.TSMC, DRCTemplate.SPACING, "P-Select", "N-Active", 2.6, null), // new DRCTemplate("PP/NP.C.1 4", DRCTemplate.TSMC, DRCTemplate.SPACING, "N-Select", "P-Active-Well", 2.6, null), // new DRCTemplate("PP/NP.C.1 4", DRCTemplate.TSMC, DRCTemplate.SPACING, "N-Select", "P-Active", 2.6, null), new DRCTemplate("5.1 Mosis", DRCTemplate.MOSIS, DRCTemplate.MINWID, "Poly-Cut", null, 2, null), new DRCTemplate("5.1 TSMC", DRCTemplate.TSMC, DRCTemplate.MINWID, "Poly-Cut", null, 2.2, null), new DRCTemplate("5.2 Mosis/TSMC", DRCTemplate.NAC, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.2 Mosis/TSMC", DRCTemplate.NAC, DRCTemplate.SURROUND, "Polysilicon-1", "Metal-1", 0.5,"Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.5,"Metal-1-Polysilicon-1-Con"), new DRCTemplate("CO.E.2-M1.E.2 TSMC", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.4,"Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.2b", DRCTemplate.AC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "Polysilicon-1", "Metal-1", 0, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.2b", DRCTemplate.AC, DRCTemplate.CUTSUR, null, null, 1, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.3", DRCTemplate.DE, DRCTemplate.CUTSPA, null, null, 4, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.3", DRCTemplate.DE, DRCTemplate.SPACING, "Poly-Cut", "Poly-Cut", 4, null), new DRCTemplate("5.3,6.3", DRCTemplate.DE|DRCTemplate.NAC, DRCTemplate.SPACING, "Active-Cut", "Poly-Cut", 4, null), new DRCTemplate("5.3", DRCTemplate.SC, DRCTemplate.CUTSPA, null, null, 2, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.3", DRCTemplate.SC, DRCTemplate.SPACING, "Poly-Cut", "Poly-Cut", 2, null), new DRCTemplate("5.3,6.3", DRCTemplate.SC|DRCTemplate.NAC, DRCTemplate.SPACING, "Active-Cut", "Poly-Cut", 2, null), // Mosis Submicron new DRCTemplate("5.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 3, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.SPACING, "Poly-Cut", "Poly-Cut", 3, null), new DRCTemplate("5.3,6.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.NAC, DRCTemplate.SPACING, "Active-Cut", "Poly-Cut", 3, null), // TSMC Submicron new DRCTemplate("5.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 2.8, "Metal-1-Polysilicon-1-Con"), new DRCTemplate("5.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.SPACING, "Poly-Cut", "Poly-Cut", 2.8, null), new DRCTemplate("5.3,6.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.NAC, DRCTemplate.SPACING, "Active-Cut", "Poly-Cut", 2.8, null), new DRCTemplate("5.4 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Poly-Cut", "Transistor-Poly", 2, null), new DRCTemplate("5.4 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Poly-Cut", "Transistor-Poly", 2.2, null), new DRCTemplate("5.5b", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.AC, DRCTemplate.UCONSPA, "Poly-Cut", "Polysilicon-1", 5, null), new DRCTemplate("5.5b", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.AC, DRCTemplate.UCONSPA, "Poly-Cut", "Transistor-Poly",5, null), new DRCTemplate("5.5b", DRCTemplate.SC| DRCTemplate.AC, DRCTemplate.UCONSPA, "Poly-Cut", "Polysilicon-1", 4, null), new DRCTemplate("5.5b", DRCTemplate.SC| DRCTemplate.AC, DRCTemplate.UCONSPA, "Poly-Cut", "Transistor-Poly",4, null), new DRCTemplate("5.6b", DRCTemplate.AC, DRCTemplate.SPACING, "Poly-Cut", "P-Active", 2, null), new DRCTemplate("5.6b", DRCTemplate.AC, DRCTemplate.SPACING, "Poly-Cut", "N-Active", 2, null), new DRCTemplate("5.7b", DRCTemplate.AC, DRCTemplate.SPACINGM, "Poly-Cut", "P-Active", 3, null), new DRCTemplate("5.7b", DRCTemplate.AC, DRCTemplate.SPACINGM, "Poly-Cut", "N-Active", 3, null), new DRCTemplate("6.1 Mosis", DRCTemplate.MOSIS, DRCTemplate.MINWID, "Active-Cut", null, 2, null), new DRCTemplate("6.1 TSMC", DRCTemplate.TSMC, DRCTemplate.MINWID, "Active-Cut", null, 2.2, null), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-P-Active-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Active", "Metal-1", 0.5,"Metal-1-P-Active-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Select", "P-Active", 2, "Metal-1-P-Active-Con"), new DRCTemplate("6.2 TSMC (PP/NP.C.1)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Select", "P-Active", 2.6, "Metal-1-P-Active-Con"), new DRCTemplate("6.2", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Well", "P-Active", 6, "Metal-1-P-Active-Con"), new DRCTemplate("6.2", DRCTemplate.SC| DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Well", "P-Active", 5, "Metal-1-P-Active-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.5,"Metal-1-P-Active-Con"), new DRCTemplate("6.2 TSMC", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.4,"Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "P-Active", "Metal-1", 0, "Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "P-Select", "P-Active", 2, "Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.AC, DRCTemplate.SURROUND, "N-Well", "P-Active", 6, "Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.SC| DRCTemplate.AC, DRCTemplate.SURROUND, "N-Well", "P-Active", 5, "Metal-1-P-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.CUTSUR, null, null, 1, "Metal-1-P-Active-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-N-Active-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Active", "Metal-1", 0.5,"Metal-1-N-Active-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Select", "N-Active", 2, "Metal-1-N-Active-Con"), new DRCTemplate("6.2 TSMC (PP/NP.C.1)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Select", "N-Active", 2.6, "Metal-1-N-Active-Con"), // PP.C.3&PP/NP.E.4=1.8 new DRCTemplate("6.2", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Well", "N-Active", 6, "Metal-1-N-Active-Con"), new DRCTemplate("6.2", DRCTemplate.SC| DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Well", "N-Active", 5, "Metal-1-N-Active-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.5,"Metal-1-N-Active-Con"), new DRCTemplate("6.2 TSMC", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.4,"Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "N-Active", "Metal-1", 0, "Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "N-Select", "N-Active", 2, "Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.AC, DRCTemplate.SURROUND, "P-Well", "N-Active", 6, "Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.SC| DRCTemplate.AC, DRCTemplate.SURROUND, "P-Well", "N-Active", 5, "Metal-1-N-Active-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.CUTSUR, null, null, 1, "Metal-1-N-Active-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-P-Well-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Active-Well", "Metal-1", 0.5,"Metal-1-P-Well-Con"), // new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Active-Well", "Metal-1", 0.5,"Metal-1-P-Well-Con"), // new DRCTemplate("6.2 TSMC", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Active-Well", "Metal-1", 0.1,"Metal-1-P-Well-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Select", "P-Active-Well", 2, "Metal-1-P-Well-Con"), new DRCTemplate("6.2 TSMC (PP/NP.C.2)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Select", "P-Active-Well", 1, "Metal-1-P-Well-Con"), // PP/NP.C.2=1.0, PP/NP.C.1 4=1.8 new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Well", "P-Active-Well", 3, "Metal-1-P-Well-Con"), new DRCTemplate("6.2 TSMC (NP.E.4)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "P-Well", "P-Active-Well", 4.3, "Metal-1-P-Well-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.5,"Metal-1-P-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-P-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "P-Active-Well", "Metal-1", 0, "Metal-1-P-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "P-Select", "P-Active-Well", 2, "Metal-1-P-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "P-Well", "P-Active-Well", 3, "Metal-1-P-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.CUTSUR, null, null, 1, "Metal-1-P-Well-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-N-Well-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Active", "Metal-1", 0.5,"Metal-1-N-Well-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Select", "N-Active", 2, "Metal-1-N-Well-Con"), new DRCTemplate("6.2 TSMC (PP/NP.C.2)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Select", "N-Active", 1, "Metal-1-N-Well-Con"), new DRCTemplate("6.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Well", "N-Active", 3, "Metal-1-N-Well-Con"), new DRCTemplate("6.2 TSMC (NP.E.4)", DRCTemplate.TSMC|DRCTemplate.NAC, DRCTemplate.SURROUND, "N-Well", "N-Active", 4.3, "Metal-1-N-Well-Con"), new DRCTemplate("6.2", DRCTemplate.NAC, DRCTemplate.CUTSUR, null, null, 1.5,"Metal-1-N-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-N-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "N-Active", "Metal-1", 0, "Metal-1-N-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "N-Select", "N-Active", 2, "Metal-1-N-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.SURROUND, "N-Well", "N-Active", 3, "Metal-1-N-Well-Con"), new DRCTemplate("6.2b", DRCTemplate.AC, DRCTemplate.CUTSUR, null, null, 1, "Metal-1-N-Well-Con"), new DRCTemplate("6.3", DRCTemplate.DE, DRCTemplate.CUTSPA, null, null, 4, "Metal-1-P-Active-Con"), new DRCTemplate("6.3", DRCTemplate.DE, DRCTemplate.CUTSPA, null, null, 4, "Metal-1-N-Active-Con"), new DRCTemplate("6.3", DRCTemplate.DE, DRCTemplate.SPACING, "Active-Cut", "Active-Cut", 4, null), new DRCTemplate("6.3", DRCTemplate.SC, DRCTemplate.CUTSPA, null, null, 2, "Metal-1-P-Active-Con"), new DRCTemplate("6.3", DRCTemplate.SC, DRCTemplate.CUTSPA, null, null, 2, "Metal-1-N-Active-Con"), new DRCTemplate("6.3", DRCTemplate.SC, DRCTemplate.SPACING, "Active-Cut", "Active-Cut", 2, null), // Mosis new DRCTemplate("6.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 3, "Metal-1-P-Active-Con"), new DRCTemplate("6.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 3, "Metal-1-N-Active-Con"), new DRCTemplate("6.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.SPACING, "Active-Cut", "Active-Cut", 3, null), // TSMC new DRCTemplate("6.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 2.8, "Metal-1-P-Active-Con"), new DRCTemplate("6.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.CUTSPA, null, null, 2.8, "Metal-1-N-Active-Con"), new DRCTemplate("6.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.SPACING, "Active-Cut", "Active-Cut", 2.8, null), // new DRCTemplate("6.4", DRCTemplate.ALL, DRCTemplate.SPACING, "Active-Cut", "Transistor-Poly",2, null), new DRCTemplate("6.4 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Active-Cut", "Transistor-Poly",2, null), new DRCTemplate("6.4 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Active-Cut", "Transistor-Poly",1.8, null), new DRCTemplate("6.5b", DRCTemplate.AC, DRCTemplate.UCONSPA, "Active-Cut", "P-Active", 5, null), new DRCTemplate("6.5b", DRCTemplate.AC, DRCTemplate.UCONSPA, "Active-Cut", "N-Active", 5, null), new DRCTemplate("6.6b", DRCTemplate.AC, DRCTemplate.SPACING, "Active-Cut", "Polysilicon-1", 2, null), // 6.7b is not implemented due to complexity. See manual new DRCTemplate("6.8b", DRCTemplate.AC, DRCTemplate.SPACING, "Active-Cut", "Poly-Cut", 4, null), new DRCTemplate("7.1", DRCTemplate.ALL, DRCTemplate.MINWID, "Metal-1", null, 3, null), new DRCTemplate("M1.A.1", DRCTemplate.TSMC, DRCTemplate.AREA, "Metal-1", null, 20.2, null), // TSMC page 39 new DRCTemplate("7.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Metal-1", "Metal-1", 3, null), new DRCTemplate("7.2 TSMC (M1.S.1)", DRCTemplate.TSMC|DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACING, "Metal-1", "Metal-1", 2.3, null), new DRCTemplate("7.2", DRCTemplate.SC, DRCTemplate.SPACING, "Metal-1", "Metal-1", 2, null), // Mosis and TSMC (M1.S.2) have 6 for min spacing for long wires new DRCTemplate("7.4", DRCTemplate.DE|DRCTemplate.SU, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-1", "Metal-1", 6, -1), new DRCTemplate("7.4", DRCTemplate.SC, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-1", "Metal-1", 4, -1), new DRCTemplate("8.1", DRCTemplate.DE, DRCTemplate.CUTSIZE, null, null, 3, "Metal-1-Metal-2-Con"), new DRCTemplate("8.1", DRCTemplate.DE, DRCTemplate.NODSIZ, null, null, 5, "Metal-1-Metal-2-Con"), new DRCTemplate("8.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2, "Metal-1-Metal-2-Con"), new DRCTemplate("8.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2.6, "Metal-1-Metal-2-Con"), new DRCTemplate("8.1", DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.NODSIZ, null, null, 4, "Metal-1-Metal-2-Con"), new DRCTemplate("8.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Via1", "Via1", 3, null), new DRCTemplate("8.2 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Via1", "Via1", 2.6, null), new DRCTemplate("8.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-1", null, 1, "Metal-1-Metal-2-Con"), new DRCTemplate("8.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-1", null, 0.7, "Metal-1-Metal-2-Con"), new DRCTemplate("8.4", DRCTemplate.NSV, DRCTemplate.SPACING, "Poly-Cut", "Via1", 2, null), new DRCTemplate("8.4", DRCTemplate.NSV, DRCTemplate.SPACING, "Active-Cut", "Via1", 2, null), new DRCTemplate("8.5", DRCTemplate.NSV, DRCTemplate.SPACINGE, "Via1", "Polysilicon-1", 2, null), new DRCTemplate("8.5", DRCTemplate.NSV, DRCTemplate.SPACINGE, "Via1", "Transistor-Poly",2, null), new DRCTemplate("8.5", DRCTemplate.NSV, DRCTemplate.SPACINGE, "Via1", "Polysilicon-2", 2, null), new DRCTemplate("8.5", DRCTemplate.NSV, DRCTemplate.SPACINGE, "Via1", "P-Active", 2, null), new DRCTemplate("8.5", DRCTemplate.NSV, DRCTemplate.SPACINGE, "Via1", "N-Active", 2, null), new DRCTemplate("9.1", DRCTemplate.ALL, DRCTemplate.MINWID, "Metal-2", null, 3, null), new DRCTemplate("9.2", DRCTemplate.DE, DRCTemplate.SPACING, "Metal-2", "Metal-2", 4, null), new DRCTemplate("9.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "Metal-2", "Metal-2", 3, null), new DRCTemplate("9.2 TSMC (Mx.S.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACING, "Metal-2", "Metal-2", 2.8, null), new DRCTemplate("9.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-2", null, 1, "Metal-1-Metal-2-Con"), new DRCTemplate("9.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-2", null, 0.7, "Metal-1-Metal-2-Con"), new DRCTemplate("9.4", DRCTemplate.DE, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-2", "Metal-2", 8, -1), new DRCTemplate("9.4", DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-2", "Metal-2", 6, -1), new DRCTemplate("11.1", DRCTemplate.SU, DRCTemplate.MINWID, "Polysilicon-2", null, 7, null), new DRCTemplate("11.1", DRCTemplate.SC, DRCTemplate.MINWID, "Polysilicon-2", null, 3, null), new DRCTemplate("11.2", DRCTemplate.ALL, DRCTemplate.SPACING, "Polysilicon-2", "Polysilicon-2", 3, null), new DRCTemplate("11.3", DRCTemplate.SU, DRCTemplate.SURROUND, "Polysilicon-2", "Polysilicon-1", 5, "Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("11.3", DRCTemplate.SU, DRCTemplate.NODSIZ, null, null, 15, "Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("11.3", DRCTemplate.SU, DRCTemplate.CUTSUR, null, null, 6.5,"Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("11.3", DRCTemplate.SC, DRCTemplate.SURROUND, "Polysilicon-2", "Polysilicon-1", 2, "Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("11.3", DRCTemplate.SC, DRCTemplate.NODSIZ, null, null, 9, "Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("11.3", DRCTemplate.SC, DRCTemplate.CUTSUR, null, null, 3.5,"Metal-1-Polysilicon-1-2-Con"), new DRCTemplate("14.1", DRCTemplate.DE, DRCTemplate.CUTSIZE, null, null, 3, "Metal-2-Metal-3-Con"), new DRCTemplate("14.1", DRCTemplate.DE, DRCTemplate.MINWID, "Via2", null, 3, null), new DRCTemplate("14.1", DRCTemplate.DE, DRCTemplate.NODSIZ, null, null, 5, "Metal-2-Metal-3-Con"), new DRCTemplate("14.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2, "Metal-2-Metal-3-Con"), new DRCTemplate("14.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2.6, "Metal-2-Metal-3-Con"), new DRCTemplate("14.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Via2", null, 2, null), new DRCTemplate("14.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Via2", null, 2.6, null), new DRCTemplate("14.1", DRCTemplate.SU|DRCTemplate.SC| DRCTemplate.M23, DRCTemplate.NODSIZ, null, null, 6, "Metal-2-Metal-3-Con"), new DRCTemplate("14.1", DRCTemplate.SU|DRCTemplate.SC| DRCTemplate.M456, DRCTemplate.NODSIZ, null, null, 4, "Metal-2-Metal-3-Con"), new DRCTemplate("14.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Via2", "Via2", 3, null), new DRCTemplate("14.2 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Via2", "Via2", 2.6, null), new DRCTemplate("14.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-2", null, 1, "Metal-2-Metal-3-Con"), new DRCTemplate("14.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-2", null, 0.7, "Metal-2-Metal-3-Con"), new DRCTemplate("14.4", DRCTemplate.SU|DRCTemplate.SC|DRCTemplate.NSV, DRCTemplate.SPACING, "Via1", "Via2", 2, null), /// ?? might need attention new DRCTemplate("15.1", DRCTemplate.SC| DRCTemplate.M3, DRCTemplate.MINWID, "Metal-3", null, 6, null), new DRCTemplate("15.1", DRCTemplate.SU| DRCTemplate.M3, DRCTemplate.MINWID, "Metal-3", null, 5, null), new DRCTemplate("15.1", DRCTemplate.SC| DRCTemplate.M456, DRCTemplate.MINWID, "Metal-3", null, 3, null), new DRCTemplate("15.1", DRCTemplate.SU| DRCTemplate.M456, DRCTemplate.MINWID, "Metal-3", null, 3, null), new DRCTemplate("15.1", DRCTemplate.DE, DRCTemplate.MINWID, "Metal-3", null, 3, null), new DRCTemplate("15.2", DRCTemplate.DE, DRCTemplate.SPACING, "Metal-3", "Metal-3", 4, null), new DRCTemplate("15.2 MOSIS", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.SPACING, "Metal-3", "Metal-3", 3, null), new DRCTemplate("15.2 TSMC (Mx.S.1)", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.SPACING, "Metal-3", "Metal-3", 2.8, null), new DRCTemplate("15.2", DRCTemplate.SC|DRCTemplate.M3, DRCTemplate.SPACING, "Metal-3", "Metal-3", 4, null), new DRCTemplate("15.2", DRCTemplate.SC|DRCTemplate.M456, DRCTemplate.SPACING, "Metal-3", "Metal-3", 3, null), new DRCTemplate("15.3", DRCTemplate.DE, DRCTemplate.VIASUR, "Metal-3", null, 1, "Metal-2-Metal-3-Con"), new DRCTemplate("15.3", DRCTemplate.SU|DRCTemplate.SC| DRCTemplate.M3, DRCTemplate.VIASUR, "Metal-3", null, 2, "Metal-2-Metal-3-Con"), new DRCTemplate("15.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC| DRCTemplate.M456, DRCTemplate.VIASUR, "Metal-3", null, 1, "Metal-2-Metal-3-Con"), new DRCTemplate("15.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC| DRCTemplate.M456, DRCTemplate.VIASUR, "Metal-3", null, 0.7, "Metal-2-Metal-3-Con"), new DRCTemplate("15.4", DRCTemplate.DE, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-3", "Metal-3", 8, -1), new DRCTemplate("15.4", DRCTemplate.SU, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-3", "Metal-3", 6, -1), new DRCTemplate("15.4", DRCTemplate.SC|DRCTemplate.M3, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-3", "Metal-3", 8, -1), new DRCTemplate("15.4", DRCTemplate.SC|DRCTemplate.M456, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-3", "Metal-3", 6, -1), new DRCTemplate("21.1", DRCTemplate.DE, DRCTemplate.CUTSIZE, null, null, 3, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1", DRCTemplate.DE, DRCTemplate.MINWID, "Via3", null, 3, null), new DRCTemplate("21.1", DRCTemplate.DE, DRCTemplate.NODSIZ, null, null, 5, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.CUTSIZE, null, null, 2.6, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Via3", null, 2, null), new DRCTemplate("21.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.SC, DRCTemplate.MINWID, "Via3", null, 2.6, null), new DRCTemplate("21.1", DRCTemplate.SU|DRCTemplate.M4, DRCTemplate.NODSIZ, null, null, 6, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1", DRCTemplate.SU|DRCTemplate.M56, DRCTemplate.NODSIZ, null, null, 4, "Metal-3-Metal-4-Con"), new DRCTemplate("21.1", DRCTemplate.SC, DRCTemplate.NODSIZ, null, null, 6, "Metal-3-Metal-4-Con"), new DRCTemplate("21.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Via3", "Via3", 3, null), new DRCTemplate("21.2 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Via3", "Via3", 2.6, null), new DRCTemplate("21.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-3", null, 1, "Metal-3-Metal-4-Con"), new DRCTemplate("21.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-3", null, 0.7, "Metal-3-Metal-4-Con"), new DRCTemplate("22.1", DRCTemplate.M4, DRCTemplate.MINWID, "Metal-4", null, 6, null), new DRCTemplate("22.1", DRCTemplate.M56, DRCTemplate.MINWID, "Metal-4", null, 3, null), new DRCTemplate("22.2", DRCTemplate.M4, DRCTemplate.SPACING, "Metal-4", "Metal-4", 6, null), new DRCTemplate("22.2", DRCTemplate.DE|DRCTemplate.M56, DRCTemplate.SPACING, "Metal-4", "Metal-4", 4, null), new DRCTemplate("22.2 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.M56, DRCTemplate.SPACING, "Metal-4", "Metal-4", 3, null), new DRCTemplate("22.2 TSMC (Mx.S.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.M56, DRCTemplate.SPACING, "Metal-4", "Metal-4", 2.8, null), new DRCTemplate("22.3", DRCTemplate.M4, DRCTemplate.VIASUR, "Metal-4", null, 2, "Metal-3-Metal-4-Con"), new DRCTemplate("22.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.M56, DRCTemplate.VIASUR, "Metal-4", null, 1, "Metal-3-Metal-4-Con"), new DRCTemplate("22.3 TSMC", DRCTemplate.TSMC|DRCTemplate.M56, DRCTemplate.VIASUR, "Metal-4", null, 0.7, "Metal-3-Metal-4-Con"), new DRCTemplate("22.4", DRCTemplate.M4, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-4", "Metal-4", 12, -1), new DRCTemplate("22.4", DRCTemplate.DE|DRCTemplate.M56, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-4", "Metal-4", 8, -1), new DRCTemplate("22.4", DRCTemplate.SU|DRCTemplate.M56, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-4", "Metal-4", 6, -1), new DRCTemplate("24.1", DRCTemplate.ALL, DRCTemplate.MINWID, "Thick-Active", null, 4, null), new DRCTemplate("24.2", DRCTemplate.ALL, DRCTemplate.SPACING, "Thick-Active", "Thick-Active", 4, null), new DRCTemplate("25.1", DRCTemplate.DE, DRCTemplate.CUTSIZE, null, null, 3, "Metal-4-Metal-5-Con"), new DRCTemplate("25.1", DRCTemplate.DE, DRCTemplate.MINWID, "Via4", null, 3, null), new DRCTemplate("25.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.CUTSIZE, null, null, 2, "Metal-4-Metal-5-Con"), new DRCTemplate("25.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.CUTSIZE, null, null, 2.6, "Metal-4-Metal-5-Con"), new DRCTemplate("25.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.MINWID, "Via4", null, 2, null), new DRCTemplate("25.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.NODSIZ, null, null, 4, "Metal-4-Metal-5-Con"), new DRCTemplate("25.1", DRCTemplate.DE|DRCTemplate.M5, DRCTemplate.NODSIZ, null, null, 7, "Metal-4-Metal-5-Con"), new DRCTemplate("25.1", DRCTemplate.DE|DRCTemplate.M6, DRCTemplate.NODSIZ, null, null, 5, "Metal-4-Metal-5-Con"), // Bug even in C-Electric It was SPACINGW originally new DRCTemplate("25.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Via4", "Via4", 3, null), new DRCTemplate("25.2 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Via4", "Via4", 2.6, null), new DRCTemplate("25.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-4", null, 1, "Metal-4-Metal-5-Con"), new DRCTemplate("25.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-4", null, 0.7, "Metal-4-Metal-5-Con"), new DRCTemplate("26.1", DRCTemplate.M5, DRCTemplate.MINWID, "Metal-5", null, 4, null), new DRCTemplate("26.1", DRCTemplate.M6, DRCTemplate.MINWID, "Metal-5", null, 3, null), new DRCTemplate("26.2", DRCTemplate.M5, DRCTemplate.SPACING, "Metal-5", "Metal-5", 4, null), new DRCTemplate("26.2", DRCTemplate.DE|DRCTemplate.M6, DRCTemplate.SPACING, "Metal-5", "Metal-5", 4, null), new DRCTemplate("26.2 MOSIS", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.M6, DRCTemplate.SPACING, "Metal-5", "Metal-5", 3, null), new DRCTemplate("26.2 TSMC (Mx.S.1)", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.M6, DRCTemplate.SPACING, "Metal-5", "Metal-5", 2.8, null), new DRCTemplate("26.3", DRCTemplate.DE|DRCTemplate.M5, DRCTemplate.VIASUR, "Metal-5", null, 2, "Metal-4-Metal-5-Con"), new DRCTemplate("26.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU|DRCTemplate.M5, DRCTemplate.VIASUR, "Metal-5", null, 1, "Metal-4-Metal-5-Con"), new DRCTemplate("26.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU|DRCTemplate.M5, DRCTemplate.VIASUR, "Metal-5", null, 0.7, "Metal-4-Metal-5-Con"), new DRCTemplate("26.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.M6, DRCTemplate.VIASUR, "Metal-5", null, 1, "Metal-4-Metal-5-Con"), new DRCTemplate("26.3 TSMC", DRCTemplate.TSMC|DRCTemplate.M6, DRCTemplate.VIASUR, "Metal-5", null, 0.7, "Metal-4-Metal-5-Con"), new DRCTemplate("26.4", DRCTemplate.M5, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-5", "Metal-5", 8, -1), new DRCTemplate("26.4", DRCTemplate.DE|DRCTemplate.M6, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-5", "Metal-5", 8, -1), new DRCTemplate("26.4", DRCTemplate.SU|DRCTemplate.M6, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-5", "Metal-5", 6, -1), new DRCTemplate("29.1", DRCTemplate.DE, DRCTemplate.CUTSIZE, null, null, 4, "Metal-5-Metal-6-Con"), new DRCTemplate("29.1", DRCTemplate.DE, DRCTemplate.MINWID, "Via5", null, 4, null), new DRCTemplate("29.1", DRCTemplate.DE, DRCTemplate.NODSIZ, null, null, 8, "Metal-5-Metal-6-Con"), new DRCTemplate("29.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.CUTSIZE, null, null, 3, "Metal-5-Metal-6-Con"), new DRCTemplate("29.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.CUTSIZE, null, null, 3.6, "Metal-5-Metal-6-Con"), new DRCTemplate("29.1 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.MINWID, "Via5", null, 3, null), new DRCTemplate("29.1 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.MINWID, "Via5", null, 3.6, null), new DRCTemplate("29.1", DRCTemplate.SU, DRCTemplate.NODSIZ, null, null, 5, "Metal-5-Metal-6-Con"), new DRCTemplate("29.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Via5", "Via5", 4, null), new DRCTemplate("29.2 TSMC", DRCTemplate.TSMC, DRCTemplate.SPACING, "Via5", "Via5", 3.6, null), new DRCTemplate("29.3 Mosis", DRCTemplate.MOSIS, DRCTemplate.VIASUR, "Metal-5", null, 1, "Metal-5-Metal-6-Con"), new DRCTemplate("29.3 TSMC", DRCTemplate.TSMC, DRCTemplate.VIASUR, "Metal-5", null, 0.9, "Metal-5-Metal-6-Con"), new DRCTemplate("30.1 Mosis", DRCTemplate.MOSIS, DRCTemplate.MINWID, "Metal-6", null, 5, null), new DRCTemplate("30.1 TSMC", DRCTemplate.TSMC, DRCTemplate.MINWID, "Metal-6", null, 4.4, null), new DRCTemplate("30.2 Mosis", DRCTemplate.MOSIS, DRCTemplate.SPACING, "Metal-6", "Metal-6", 5, null), new DRCTemplate("30.2 TSMC (M6.S.1)", DRCTemplate.TSMC, DRCTemplate.SPACING, "Metal-6", "Metal-6", 4.6, null), new DRCTemplate("30.3", DRCTemplate.DE, DRCTemplate.VIASUR, "Metal-6", null, 2, "Metal-5-Metal-6-Con"), new DRCTemplate("30.3 Mosis", DRCTemplate.MOSIS|DRCTemplate.SU, DRCTemplate.VIASUR, "Metal-6", null, 1, "Metal-5-Metal-6-Con"), new DRCTemplate("30.3 TSMC", DRCTemplate.TSMC|DRCTemplate.SU, DRCTemplate.VIASUR, "Metal-6", null, 0.9, "Metal-5-Metal-6-Con"), new DRCTemplate("30.4", DRCTemplate.ALL, DRCTemplate.SPACINGW, WIDELIMIT, 0, "Metal-6", "Metal-6", 10, -1) }; // -------------------- private and protected methods ------------------------ private MoCMOS() { super("mocmos"); setTechShortName("MOSIS CMOS"); setTechDesc("MOSIS CMOS"); setFactoryScale(200, true); // in nanometers: really 0.2 micron setNoNegatedArcs(); setStaticTechnology(); setFactoryTransparentLayers(new Color [] { new Color( 96,209,255), // Metal-1 new Color(255,155,192), // Polysilicon-1 new Color(107,226, 96), // Active new Color(224, 95,255), // Metal-2 new Color(247,251, 20) // Metal-3 }); setFactoryResolution(0.01); // value in lambdas 0.005um -> 0.05 lambdas foundries.add(new Foundry(Foundry.MOSIS_FOUNDRY, DRCTemplate.MOSIS)); foundries.add(new Foundry("TSMC", DRCTemplate.TSMC)); setFactorySelecedFound(Foundry.MOSIS_FOUNDRY); // default //**************************************** LAYERS **************************************** Layer[] metalLayers = new Layer[6]; // 1 -> 6 /** metal-1 layer */ metalLayers[0] = Layer.newInstance(this, "Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-2 layer */ metalLayers[1] = Layer.newInstance(this, "Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** metal-3 layer */ metalLayers[2] = Layer.newInstance(this, "Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-4 layer */ metalLayers[3] = Layer.newInstance(this, "Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** metal-5 layer */ metalLayers[4] = Layer.newInstance(this, "Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** metal-6 layer */ metalLayers[5] = Layer.newInstance(this, "Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** poly layer */ poly1_lay = Layer.newInstance(this, "Polysilicon-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly2 layer */ Layer poly2_lay = Layer.newInstance(this, "Polysilicon-2", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X Layer[] activeLayers = new Layer[2]; /** P active layer */ activeLayers[P_TYPE] = Layer.newInstance(this, "P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** N active layer */ activeLayers[N_TYPE] = Layer.newInstance(this, "N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX Layer[] selectLayers = new Layer[2]; /** P Select layer */ selectLayers[P_TYPE] = Layer.newInstance(this, "P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** N Select layer */ selectLayers[N_TYPE] = Layer.newInstance(this, "N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// Layer[] wellLayers = new Layer[2]; /** P Well layer */ wellLayers[P_TYPE] = Layer.newInstance(this, "P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** N Well implant */ wellLayers[N_TYPE] = Layer.newInstance(this, "N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** poly cut layer */ Layer polyCutLayer = Layer.newInstance(this, "Poly-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** active cut layer */ Layer activeCut_lay = Layer.newInstance(this, "Active-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via1 layer */ Layer via1_lay = Layer.newInstance(this, "Via1", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via2 layer */ Layer via2_lay = Layer.newInstance(this, "Via2", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via3 layer */ Layer via3_lay = Layer.newInstance(this, "Via3", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via4 layer */ Layer via4_lay = Layer.newInstance(this, "Via4", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via5 layer */ Layer via5_lay = Layer.newInstance(this, "Via5", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** passivation layer */ Layer passivation_lay = Layer.newInstance(this, "Passivation", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 100,100,100, 1.0,true, new int[] { 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000, // 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000}));// /** poly/trans layer */ transistorPoly_lay = Layer.newInstance(this, "Transistor-Poly", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly cap layer */ Layer polyCap_lay = Layer.newInstance(this, "Poly-Cap", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 0,0,0, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** P act well layer */ Layer pActiveWell_lay = Layer.newInstance(this, "P-Active-Well", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,false, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** Silicide block */ /** Resist Protection Oxide (RPO) Same graphics as in 90nm tech */ Layer silicideBlock_lay = Layer.newInstance(this, "Silicide-Block", // new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 230,230,230, 1.0,false, // new int[] { 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000}));// new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 192,255,255, 0.5,true, new int[] { 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000, /* */ 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000}));/* */ /** Thick active */ Layer thickActive_lay = Layer.newInstance(this, "Thick-Active", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,0,0, 1.0,false, new int[] { 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020}));// X X /** pseudo metal 1 */ Layer pseudoMetal1_lay = Layer.newInstance(this, "Pseudo-Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** pseudo metal-2 */ Layer pseudoMetal2_lay = Layer.newInstance(this, "Pseudo-Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-3 */ Layer pseudoMetal3_lay = Layer.newInstance(this, "Pseudo-Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-4 */ Layer pseudoMetal4_lay = Layer.newInstance(this, "Pseudo-Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** pseudo metal-5 */ Layer pseudoMetal5_lay = Layer.newInstance(this, "Pseudo-Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** pseudo metal-6 */ Layer pseudoMetal6_lay = Layer.newInstance(this, "Pseudo-Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** pseudo poly layer */ Layer pseudoPoly1_lay = Layer.newInstance(this, "Pseudo-Polysilicon", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 1.0,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** pseudo poly2 layer */ Layer pseudoPoly2_lay = Layer.newInstance(this, "Pseudo-Electrode", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X /** pseudo P active */ Layer pseudoPActive_lay = Layer.newInstance(this, "Pseudo-P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo N active */ Layer pseudoNActive_lay = Layer.newInstance(this, "Pseudo-N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo P Select */ Layer pseudoPSelect_lay = Layer.newInstance(this, "Pseudo-P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo N Select */ Layer pseudoNSelect_lay = Layer.newInstance(this, "Pseudo-N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// /** pseudo P Well */ Layer pseudoPWell_lay = Layer.newInstance(this, "Pseudo-P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** pseudo N Well */ Layer pseudoNWell_lay = Layer.newInstance(this, "Pseudo-N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** pad frame */ Layer padFrame_lay = Layer.newInstance(this, "Pad-Frame", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, 0, 255,0,0, 1.0,false, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); // The layer functions metalLayers[0].setFunction(Layer.Function.METAL1); // Metal-1 metalLayers[1].setFunction(Layer.Function.METAL2); // Metal-2 metalLayers[2].setFunction(Layer.Function.METAL3); // Metal-3 metalLayers[3].setFunction(Layer.Function.METAL4); // Metal-4 metalLayers[4].setFunction(Layer.Function.METAL5); // Metal-5 metalLayers[5].setFunction(Layer.Function.METAL6); // Metal-6 poly1_lay.setFunction(Layer.Function.POLY1); // Polysilicon-1 poly2_lay.setFunction(Layer.Function.POLY2); // Polysilicon-2 activeLayers[P_TYPE].setFunction(Layer.Function.DIFFP); // P-Active activeLayers[N_TYPE].setFunction(Layer.Function.DIFFN); // N-Active selectLayers[P_TYPE].setFunction(Layer.Function.IMPLANTP); // P-Select selectLayers[N_TYPE].setFunction(Layer.Function.IMPLANTN); // N-Select wellLayers[P_TYPE].setFunction(Layer.Function.WELLP); // P-Well wellLayers[N_TYPE].setFunction(Layer.Function.WELLN); // N-Well polyCutLayer.setFunction(Layer.Function.CONTACT1, Layer.Function.CONPOLY); // Poly-Cut activeCut_lay.setFunction(Layer.Function.CONTACT1, Layer.Function.CONDIFF); // Active-Cut via1_lay.setFunction(Layer.Function.CONTACT2, Layer.Function.CONMETAL); // Via-1 via2_lay.setFunction(Layer.Function.CONTACT3, Layer.Function.CONMETAL); // Via-2 via3_lay.setFunction(Layer.Function.CONTACT4, Layer.Function.CONMETAL); // Via-3 via4_lay.setFunction(Layer.Function.CONTACT5, Layer.Function.CONMETAL); // Via-4 via5_lay.setFunction(Layer.Function.CONTACT6, Layer.Function.CONMETAL); // Via-5 passivation_lay.setFunction(Layer.Function.OVERGLASS); // Passivation transistorPoly_lay.setFunction(Layer.Function.GATE); // Transistor-Poly polyCap_lay.setFunction(Layer.Function.CAP); // Poly-Cap pActiveWell_lay.setFunction(Layer.Function.DIFFP); // P-Active-Well silicideBlock_lay.setFunction(Layer.Function.ART); // Silicide-Block thickActive_lay.setFunction(Layer.Function.DIFF, Layer.Function.THICK); // Thick-Active pseudoMetal1_lay.setFunction(Layer.Function.METAL1, Layer.Function.PSEUDO); // Pseudo-Metal-1 pseudoMetal2_lay.setFunction(Layer.Function.METAL2, Layer.Function.PSEUDO); // Pseudo-Metal-2 pseudoMetal3_lay.setFunction(Layer.Function.METAL3, Layer.Function.PSEUDO); // Pseudo-Metal-3 pseudoMetal4_lay.setFunction(Layer.Function.METAL4, Layer.Function.PSEUDO); // Pseudo-Metal-4 pseudoMetal5_lay.setFunction(Layer.Function.METAL5, Layer.Function.PSEUDO); // Pseudo-Metal-5 pseudoMetal6_lay.setFunction(Layer.Function.METAL6, Layer.Function.PSEUDO); // Pseudo-Metal-6 pseudoPoly1_lay.setFunction(Layer.Function.POLY1, Layer.Function.PSEUDO); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFunction(Layer.Function.POLY2, Layer.Function.PSEUDO); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFunction(Layer.Function.DIFFP, Layer.Function.PSEUDO); // Pseudo-P-Active pseudoNActive_lay.setFunction(Layer.Function.DIFFN, Layer.Function.PSEUDO); // Pseudo-N-Active pseudoPSelect_lay.setFunction(Layer.Function.IMPLANTP, Layer.Function.PSEUDO); // Pseudo-P-Select pseudoNSelect_lay.setFunction(Layer.Function.IMPLANTN, Layer.Function.PSEUDO); // Pseudo-N-Select pseudoPWell_lay.setFunction(Layer.Function.WELLP, Layer.Function.PSEUDO); // Pseudo-P-Well pseudoNWell_lay.setFunction(Layer.Function.WELLN, Layer.Function.PSEUDO); // Pseudo-N-Well padFrame_lay.setFunction(Layer.Function.ART); // Pad-Frame // The CIF names metalLayers[0].setFactoryCIFLayer("CMF"); // Metal-1 metalLayers[1].setFactoryCIFLayer("CMS"); // Metal-2 metalLayers[2].setFactoryCIFLayer("CMT"); // Metal-3 metalLayers[3].setFactoryCIFLayer("CMQ"); // Metal-4 metalLayers[4].setFactoryCIFLayer("CMP"); // Metal-5 metalLayers[5].setFactoryCIFLayer("CM6"); // Metal-6 poly1_lay.setFactoryCIFLayer("CPG"); // Polysilicon-1 poly2_lay.setFactoryCIFLayer("CEL"); // Polysilicon-2 activeLayers[P_TYPE].setFactoryCIFLayer("CAA"); // P-Active activeLayers[N_TYPE].setFactoryCIFLayer("CAA"); // N-Active selectLayers[P_TYPE].setFactoryCIFLayer("CSP"); // P-Select selectLayers[N_TYPE].setFactoryCIFLayer("CSN"); // N-Select wellLayers[P_TYPE].setFactoryCIFLayer("CWP"); // P-Well wellLayers[N_TYPE].setFactoryCIFLayer("CWN"); // N-Well polyCutLayer.setFactoryCIFLayer("CCC"); // Poly-Cut activeCut_lay.setFactoryCIFLayer("CCC"); // Active-Cut via1_lay.setFactoryCIFLayer("CVA"); // Via-1 via2_lay.setFactoryCIFLayer("CVS"); // Via-2 via3_lay.setFactoryCIFLayer("CVT"); // Via-3 via4_lay.setFactoryCIFLayer("CVQ"); // Via-4 via5_lay.setFactoryCIFLayer("CV5"); // Via-5 passivation_lay.setFactoryCIFLayer("COG"); // Passivation transistorPoly_lay.setFactoryCIFLayer("CPG"); // Transistor-Poly polyCap_lay.setFactoryCIFLayer("CPC"); // Poly-Cap pActiveWell_lay.setFactoryCIFLayer("CAA"); // P-Active-Well silicideBlock_lay.setFactoryCIFLayer("CSB"); // Silicide-Block thickActive_lay.setFactoryCIFLayer("CTA"); // Thick-Active pseudoMetal1_lay.setFactoryCIFLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryCIFLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryCIFLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryCIFLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryCIFLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryCIFLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryCIFLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactoryCIFLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactoryCIFLayer("CSP"); // Pseudo-P-Select pseudoNSelect_lay.setFactoryCIFLayer("CSN"); // Pseudo-N-Select pseudoPWell_lay.setFactoryCIFLayer("CWP"); // Pseudo-P-Well pseudoNWell_lay.setFactoryCIFLayer("CWN"); // Pseudo-N-Well padFrame_lay.setFactoryCIFLayer("XP"); // Pad-Frame // The GDS names metalLayers[0].setFactoryGDSLayer("49, 80p, 80t", Foundry.MOSIS_FOUNDRY); // Metal-1 Mosis metalLayers[0].setFactoryGDSLayer("16", Foundry.TSMC_FOUNDRY); // Metal-1 TSMC metalLayers[1].setFactoryGDSLayer("51, 82p, 82t", Foundry.MOSIS_FOUNDRY); // Metal-2 metalLayers[1].setFactoryGDSLayer("18", Foundry.TSMC_FOUNDRY); // Metal-2 metalLayers[2].setFactoryGDSLayer("62, 93p, 93t", Foundry.MOSIS_FOUNDRY); // Metal-3 metalLayers[2].setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Metal-3 metalLayers[3].setFactoryGDSLayer("31, 63p, 63t", Foundry.MOSIS_FOUNDRY); // Metal-4 metalLayers[3].setFactoryGDSLayer("31", Foundry.TSMC_FOUNDRY); metalLayers[4].setFactoryGDSLayer("33, 64p, 64t", Foundry.MOSIS_FOUNDRY); // Metal-5 metalLayers[4].setFactoryGDSLayer("33", Foundry.TSMC_FOUNDRY); // Metal-5 metalLayers[5].setFactoryGDSLayer("37, 68p, 68t", Foundry.MOSIS_FOUNDRY); // Metal-6 metalLayers[5].setFactoryGDSLayer("38", Foundry.TSMC_FOUNDRY); // Metal-6 poly1_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Polysilicon-1 poly1_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Polysilicon-1 transistorPoly_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Transistor-Poly transistorPoly_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Transistor-Poly poly2_lay.setFactoryGDSLayer("56", Foundry.MOSIS_FOUNDRY); // Polysilicon-2 activeLayers[P_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active activeLayers[P_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active activeLayers[N_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // N-Active activeLayers[N_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // N-Active pActiveWell_lay.setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active-Well pActiveWell_lay.setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active-Well selectLayers[P_TYPE].setFactoryGDSLayer("44", Foundry.MOSIS_FOUNDRY); // P-Select selectLayers[P_TYPE].setFactoryGDSLayer("7", Foundry.TSMC_FOUNDRY); // P-Select selectLayers[N_TYPE].setFactoryGDSLayer("45", Foundry.MOSIS_FOUNDRY); // N-Select selectLayers[N_TYPE].setFactoryGDSLayer("8", Foundry.TSMC_FOUNDRY); // N-Select wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.MOSIS_FOUNDRY); // P-Well wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.TSMC_FOUNDRY); // P-Well wellLayers[N_TYPE].setFactoryGDSLayer("42", Foundry.MOSIS_FOUNDRY); // N-Well wellLayers[N_TYPE].setFactoryGDSLayer("2", Foundry.TSMC_FOUNDRY); // N-Well polyCutLayer.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Poly-Cut polyCutLayer.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Poly-Cut activeCut_lay.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Active-Cut activeCut_lay.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Active-Cut via1_lay.setFactoryGDSLayer("50", Foundry.MOSIS_FOUNDRY); // Via-1 via1_lay.setFactoryGDSLayer("17", Foundry.TSMC_FOUNDRY); // Via-1 via2_lay.setFactoryGDSLayer("61", Foundry.MOSIS_FOUNDRY); // Via-2 via2_lay.setFactoryGDSLayer("27", Foundry.TSMC_FOUNDRY); // Via-2 via3_lay.setFactoryGDSLayer("30", Foundry.MOSIS_FOUNDRY); // Via-3 via3_lay.setFactoryGDSLayer("29", Foundry.TSMC_FOUNDRY); // Via-3 via4_lay.setFactoryGDSLayer("32", Foundry.MOSIS_FOUNDRY); // Via-4 via4_lay.setFactoryGDSLayer("32", Foundry.TSMC_FOUNDRY); // Via-4 via5_lay.setFactoryGDSLayer("36", Foundry.MOSIS_FOUNDRY); // Via-5 via5_lay.setFactoryGDSLayer("39", Foundry.TSMC_FOUNDRY); // Via-5 passivation_lay.setFactoryGDSLayer("52", Foundry.MOSIS_FOUNDRY); // Passivation passivation_lay.setFactoryGDSLayer("19", Foundry.TSMC_FOUNDRY); // Passivation polyCap_lay.setFactoryGDSLayer("28", Foundry.MOSIS_FOUNDRY); // Poly-Cap polyCap_lay.setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Poly-Cap silicideBlock_lay.setFactoryGDSLayer("29", Foundry.MOSIS_FOUNDRY); // Silicide-Block silicideBlock_lay.setFactoryGDSLayer("34", Foundry.TSMC_FOUNDRY); // Silicide-Block thickActive_lay.setFactoryGDSLayer("60", Foundry.MOSIS_FOUNDRY); // Thick-Active thickActive_lay.setFactoryGDSLayer("4", Foundry.TSMC_FOUNDRY); // Thick-Active pseudoMetal1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Active pseudoNActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Active pseudoPSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Select pseudoNSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Select pseudoPWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Well pseudoNWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Well padFrame_lay.setFactoryGDSLayer("26", Foundry.MOSIS_FOUNDRY); // Pad-Frame padFrame_lay.setFactoryGDSLayer("26", Foundry.TSMC_FOUNDRY); // Pad-Frame // The Skill names metalLayers[0].setFactorySkillLayer("metal1"); // Metal-1 metalLayers[1].setFactorySkillLayer("metal2"); // Metal-2 metalLayers[2].setFactorySkillLayer("metal3"); // Metal-3 metalLayers[3].setFactorySkillLayer("metal4"); // Metal-4 metalLayers[4].setFactorySkillLayer("metal5"); // Metal-5 metalLayers[5].setFactorySkillLayer("metal6"); // Metal-6 poly1_lay.setFactorySkillLayer("poly"); // Polysilicon-1 poly2_lay.setFactorySkillLayer(""); // Polysilicon-2 activeLayers[P_TYPE].setFactorySkillLayer("aa"); // P-Active activeLayers[N_TYPE].setFactorySkillLayer("aa"); // N-Active selectLayers[P_TYPE].setFactorySkillLayer("pplus"); // P-Select selectLayers[N_TYPE].setFactorySkillLayer("nplus"); // N-Select wellLayers[P_TYPE].setFactorySkillLayer("pwell"); // P-Well wellLayers[N_TYPE].setFactorySkillLayer("nwell"); // N-Well polyCutLayer.setFactorySkillLayer("pcont"); // Poly-Cut activeCut_lay.setFactorySkillLayer("acont"); // Active-Cut via1_lay.setFactorySkillLayer("via"); // Via-1 via2_lay.setFactorySkillLayer("via2"); // Via-2 via3_lay.setFactorySkillLayer("via3"); // Via-3 via4_lay.setFactorySkillLayer("via4"); // Via-4 via5_lay.setFactorySkillLayer("via5"); // Via-5 passivation_lay.setFactorySkillLayer("glasscut"); // Passivation transistorPoly_lay.setFactorySkillLayer("poly"); // Transistor-Poly polyCap_lay.setFactorySkillLayer(""); // Poly-Cap pActiveWell_lay.setFactorySkillLayer("aa"); // P-Active-Well silicideBlock_lay.setFactorySkillLayer(""); // Silicide-Block thickActive_lay.setFactorySkillLayer(""); // Thick-Active pseudoMetal1_lay.setFactorySkillLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactorySkillLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactorySkillLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactorySkillLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactorySkillLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactorySkillLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactorySkillLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactorySkillLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactorySkillLayer("pplus"); // Pseudo-P-Select pseudoNSelect_lay.setFactorySkillLayer("nplus"); // Pseudo-N-Select pseudoPWell_lay.setFactorySkillLayer("pwell"); // Pseudo-P-Well pseudoNWell_lay.setFactorySkillLayer("nwell"); // Pseudo-N-Well padFrame_lay.setFactorySkillLayer(""); // Pad-Frame // The layer distance // Data base on 18nm technology with 200nm as grid unit. double BULK_LAYER = 10; double DIFF_LAYER = 1; // dummy distance for now 0.2/0.2 double ILD_LAYER = 3.5; // 0.7/0.2 convertLength() double IMD_LAYER = 5.65; // 1.13um/0.2 double METAL_LAYER = 2.65; // 0.53um/0.2 activeLayers[P_TYPE].setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active 0.17um/0.2 = activeLayers[N_TYPE].setFactory3DInfo(0.8, BULK_LAYER + 2*DIFF_LAYER); // N-Active 0.16um/0.2 selectLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // P-Select selectLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // N-Select wellLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // P-Well wellLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // N-Well pActiveWell_lay.setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active-Well thickActive_lay.setFactory3DInfo(0.5, BULK_LAYER + 0.5); // Thick Active (between select and well) metalLayers[0].setFactory3DInfo(METAL_LAYER, ILD_LAYER + activeLayers[P_TYPE].getDepth()); // Metal-1 0.53um/0.2 metalLayers[1].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[0].getDistance()); // Metal-2 via1_lay.setFactory3DInfo(metalLayers[1].getDistance()-metalLayers[0].getDepth(), metalLayers[0].getDepth()); // Via-1 metalLayers[2].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[1].getDistance()); // Metal-3 via2_lay.setFactory3DInfo(metalLayers[2].getDistance()-metalLayers[1].getDepth(), metalLayers[1].getDepth()); // Via-2 metalLayers[3].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[2].getDistance()); // Metal-4 via3_lay.setFactory3DInfo(metalLayers[3].getDistance()-metalLayers[2].getDepth(), metalLayers[2].getDepth()); // Via-3 metalLayers[4].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[3].getDistance()); // Metal-5 via4_lay.setFactory3DInfo(metalLayers[4].getDistance()-metalLayers[3].getDepth(), metalLayers[3].getDepth()); // Via-4 metalLayers[5].setFactory3DInfo(4.95, IMD_LAYER + metalLayers[4].getDistance()); // Metal-6 0.99um/0.2 via5_lay.setFactory3DInfo(metalLayers[5].getDistance()-metalLayers[4].getDepth(), metalLayers[4].getDepth()); // Via-5 double PASS_LAYER = 5; // 1um/0.2 double PO_LAYER = 1; // 0.2/0.2 double FOX_LAYER = 1.75; // 0.35/0.2 double TOX_LAYER = 0; // Very narrow thin oxide in gate /* for displaying pins */ pseudoMetal1_lay.setFactory3DInfo(0, metalLayers[0].getDistance()); // Pseudo-Metal-1 pseudoMetal2_lay.setFactory3DInfo(0, metalLayers[1].getDistance()); // Pseudo-Metal-2 pseudoMetal3_lay.setFactory3DInfo(0, metalLayers[2].getDistance()); // Pseudo-Metal-3 pseudoMetal4_lay.setFactory3DInfo(0, metalLayers[3].getDistance()); // Pseudo-Metal-4 pseudoMetal5_lay.setFactory3DInfo(0, metalLayers[4].getDistance()); // Pseudo-Metal-5 pseudoMetal6_lay.setFactory3DInfo(0, metalLayers[5].getDistance()); // Pseudo-Metal-6 // Poly layers poly1_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Polysilicon-1 transistorPoly_lay.setFactory3DInfo(PO_LAYER, TOX_LAYER + activeLayers[P_TYPE].getDepth()); // Transistor-Poly poly2_lay.setFactory3DInfo(PO_LAYER, transistorPoly_lay.getDepth()); // Polysilicon-2 // on top of transistor layer? polyCap_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Poly-Cap @TODO GVG Ask polyCap polyCutLayer.setFactory3DInfo(metalLayers[0].getDistance()-poly1_lay.getDepth(), poly1_lay.getDepth()); // Poly-Cut between poly and metal1 activeCut_lay.setFactory3DInfo(metalLayers[0].getDistance()-activeLayers[N_TYPE].getDepth(), activeLayers[N_TYPE].getDepth()); // Active-Cut betweent active and metal1 // Other layers passivation_lay.setFactory3DInfo(PASS_LAYER, metalLayers[5].getDepth()); // Passivation silicideBlock_lay.setFactory3DInfo(0, BULK_LAYER); // Silicide-Block padFrame_lay.setFactory3DInfo(0, passivation_lay.getDepth()); // Pad-Frame pseudoPoly1_lay.setFactory3DInfo(0, poly1_lay.getDistance()); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactory3DInfo(0, poly2_lay.getDistance()); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactory3DInfo(0, activeLayers[P_TYPE].getDistance()); // Pseudo-P-Active pseudoNActive_lay.setFactory3DInfo(0, activeLayers[N_TYPE].getDistance()); // Pseudo-N-Active pseudoPSelect_lay.setFactory3DInfo(0, selectLayers[P_TYPE].getDistance()); // Pseudo-P-Select pseudoNSelect_lay.setFactory3DInfo(0, selectLayers[N_TYPE].getDistance()); // Pseudo-N-Select pseudoPWell_lay.setFactory3DInfo(0, wellLayers[P_TYPE].getDistance()); // Pseudo-P-Well pseudoNWell_lay.setFactory3DInfo(0, wellLayers[N_TYPE].getDistance()); // Pseudo-N-Well // The Spice parasitics - metalLayers[0].setFactoryParasitics(0.06, 0.07, 0); // Metal-1 - metalLayers[1].setFactoryParasitics(0.06, 0.04, 0); // Metal-2 - metalLayers[2].setFactoryParasitics(0.06, 0.04, 0); // Metal-3 - metalLayers[3].setFactoryParasitics(0.03, 0.04, 0); // Metal-4 - metalLayers[4].setFactoryParasitics(0.03, 0.04, 0); // Metal-5 - metalLayers[5].setFactoryParasitics(0.03, 0.04, 0); // Metal-6 - poly1_lay.setFactoryParasitics(2.5, 0.09, 0); // Polysilicon-1 + metalLayers[0].setFactoryParasitics(0.078, 0.1209, 0.1104); // Metal-1 + metalLayers[1].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-2 + metalLayers[2].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-3 + metalLayers[3].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-4 + metalLayers[4].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-5 + metalLayers[5].setFactoryParasitics(0.036, 0.0423, 0.1273); // Metal-6 + poly1_lay.setFactoryParasitics(6.2, 0.1467, 0.0608); // Polysilicon-1 poly2_lay.setFactoryParasitics(50.0, 1.0, 0); // Polysilicon-2 activeLayers[P_TYPE].setFactoryParasitics(2.5, 0.9, 0); // P-Active activeLayers[N_TYPE].setFactoryParasitics(3.0, 0.9, 0); // N-Active selectLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Select selectLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Select wellLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Well wellLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Well polyCutLayer.setFactoryParasitics(2.2, 0, 0); // Poly-Cut activeCut_lay.setFactoryParasitics(2.5, 0, 0); // Active-Cut via1_lay.setFactoryParasitics(1.0, 0, 0); // Via-1 via2_lay.setFactoryParasitics(0.9, 0, 0); // Via-2 via3_lay.setFactoryParasitics(0.8, 0, 0); // Via-3 via4_lay.setFactoryParasitics(0.8, 0, 0); // Via-4 via5_lay.setFactoryParasitics(0.8, 0, 0); // Via-5 passivation_lay.setFactoryParasitics(0, 0, 0); // Passivation transistorPoly_lay.setFactoryParasitics(2.5, 0.09, 0); // Transistor-Poly polyCap_lay.setFactoryParasitics(0, 0, 0); // Poly-Cap pActiveWell_lay.setFactoryParasitics(0, 0, 0); // P-Active-Well silicideBlock_lay.setFactoryParasitics(0, 0, 0); // Silicide-Block thickActive_lay.setFactoryParasitics(0, 0, 0); // Thick-Active pseudoMetal1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Active pseudoNActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Active pseudoPSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Select pseudoNSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Select pseudoPWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Well pseudoNWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Well padFrame_lay.setFactoryParasitics(0, 0, 0); // Pad-Frame - setFactoryParasitics(50, 0.04); + setFactoryParasitics(4, 0.1); String [] headerLevel1 = { "*CMOS/BULK-NWELL (PRELIMINARY PARAMETERS)", ".OPTIONS NOMOD DEFL=3UM DEFW=3UM DEFAD=70P DEFAS=70P LIMPTS=1000", "+ITL5=0 RELTOL=0.01 ABSTOL=500PA VNTOL=500UV LVLTIM=2", "+LVLCOD=1", ".MODEL N NMOS LEVEL=1", "+KP=60E-6 VTO=0.7 GAMMA=0.3 LAMBDA=0.05 PHI=0.6", "+LD=0.4E-6 TOX=40E-9 CGSO=2.0E-10 CGDO=2.0E-10 CJ=.2MF/M^2", ".MODEL P PMOS LEVEL=1", "+KP=20E-6 VTO=0.7 GAMMA=0.4 LAMBDA=0.05 PHI=0.6", "+LD=0.6E-6 TOX=40E-9 CGSO=3.0E-10 CGDO=3.0E-10 CJ=.2MF/M^2", ".MODEL DIFFCAP D CJO=.2MF/M^2" }; setSpiceHeaderLevel1(headerLevel1); String [] headerLevel2 = { "* MOSIS 3u CMOS PARAMS", ".OPTIONS NOMOD DEFL=2UM DEFW=6UM DEFAD=100P DEFAS=100P", "+LIMPTS=1000 ITL5=0 ABSTOL=500PA VNTOL=500UV", "* Note that ITL5=0 sets ITL5 to infinity", ".MODEL N NMOS LEVEL=2 LD=0.3943U TOX=502E-10", "+NSUB=1.22416E+16 VTO=0.756 KP=4.224E-05 GAMMA=0.9241", "+PHI=0.6 UO=623.661 UEXP=8.328627E-02 UCRIT=54015.0", "+DELTA=5.218409E-03 VMAX=50072.2 XJ=0.4U LAMBDA=2.975321E-02", "+NFS=4.909947E+12 NEFF=1.001E-02 NSS=0.0 TPG=1.0", "+RSH=20.37 CGDO=3.1E-10 CGSO=3.1E-10", "+CJ=3.205E-04 MJ=0.4579 CJSW=4.62E-10 MJSW=0.2955 PB=0.7", ".MODEL P PMOS LEVEL=2 LD=0.2875U TOX=502E-10", "+NSUB=1.715148E+15 VTO=-0.7045 KP=1.686E-05 GAMMA=0.3459", "+PHI=0.6 UO=248.933 UEXP=1.02652 UCRIT=182055.0", "+DELTA=1.0E-06 VMAX=100000.0 XJ=0.4U LAMBDA=1.25919E-02", "+NFS=1.0E+12 NEFF=1.001E-02 NSS=0.0 TPG=-1.0", "+RSH=79.10 CGDO=2.89E-10 CGSO=2.89E-10", "+CJ=1.319E-04 MJ=0.4125 CJSW=3.421E-10 MJSW=0.198 PB=0.66", ".TEMP 25.0" }; setSpiceHeaderLevel2(headerLevel2); //**************************************** ARCS **************************************** /** metal 1 arc */ metalArcs[0] = ArcProto.newInstance(this, "Metal-1", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[0], 0, Poly.Type.FILLED) }); metalArcs[0].setFunction(ArcProto.Function.METAL1); metalArcs[0].setFactoryFixedAngle(true); metalArcs[0].setWipable(); metalArcs[0].setFactoryAngleIncrement(90); /** metal 2 arc */ metalArcs[1] = ArcProto.newInstance(this, "Metal-2", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[1], 0, Poly.Type.FILLED) }); metalArcs[1].setFunction(ArcProto.Function.METAL2); metalArcs[1].setFactoryFixedAngle(true); metalArcs[1].setWipable(); metalArcs[1].setFactoryAngleIncrement(90); /** metal 3 arc */ metalArcs[2] = ArcProto.newInstance(this, "Metal-3", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[2], 0, Poly.Type.FILLED) }); metalArcs[2].setFunction(ArcProto.Function.METAL3); metalArcs[2].setFactoryFixedAngle(true); metalArcs[2].setWipable(); metalArcs[2].setFactoryAngleIncrement(90); /** metal 4 arc */ metalArcs[3] = ArcProto.newInstance(this, "Metal-4", 6.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[3], 0, Poly.Type.FILLED) }); metalArcs[3].setFunction(ArcProto.Function.METAL4); metalArcs[3].setFactoryFixedAngle(true); metalArcs[3].setWipable(); metalArcs[3].setFactoryAngleIncrement(90); /** metal 5 arc */ metalArcs[4] = ArcProto.newInstance(this, "Metal-5", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[4], 0, Poly.Type.FILLED) }); metalArcs[4].setFunction(ArcProto.Function.METAL5); metalArcs[4].setFactoryFixedAngle(true); metalArcs[4].setWipable(); metalArcs[4].setFactoryAngleIncrement(90); /** metal 6 arc */ metalArcs[5] = ArcProto.newInstance(this, "Metal-6", 4.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[5], 0, Poly.Type.FILLED) }); metalArcs[5].setFunction(ArcProto.Function.METAL6); metalArcs[5].setFactoryFixedAngle(true); metalArcs[5].setWipable(); metalArcs[5].setFactoryAngleIncrement(90); /** polysilicon 1 arc */ poly1_arc = ArcProto.newInstance(this, "Polysilicon-1", 2.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly1_lay, 0, Poly.Type.FILLED) }); poly1_arc.setFunction(ArcProto.Function.POLY1); poly1_arc.setFactoryFixedAngle(true); poly1_arc.setWipable(); poly1_arc.setFactoryAngleIncrement(90); /** polysilicon 2 arc */ poly2_arc = ArcProto.newInstance(this, "Polysilicon-2", 7.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly2_lay, 0, Poly.Type.FILLED) }); poly2_arc.setFunction(ArcProto.Function.POLY2); poly2_arc.setFactoryFixedAngle(true); poly2_arc.setWipable(); poly2_arc.setFactoryAngleIncrement(90); poly2_arc.setNotUsed(); /** P-active arc */ activeArcs[P_TYPE] = ArcProto.newInstance(this, "P-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[P_TYPE], 8, Poly.Type.FILLED) }); activeArcs[P_TYPE].setFunction(ArcProto.Function.DIFFP); activeArcs[P_TYPE].setFactoryFixedAngle(true); activeArcs[P_TYPE].setWipable(); activeArcs[P_TYPE].setFactoryAngleIncrement(90); activeArcs[P_TYPE].setWidthOffset(12.0); /** N-active arc */ activeArcs[N_TYPE] = ArcProto.newInstance(this, "N-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[N_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[N_TYPE], 8, Poly.Type.FILLED) }); activeArcs[N_TYPE].setFunction(ArcProto.Function.DIFFN); activeArcs[N_TYPE].setFactoryFixedAngle(true); activeArcs[N_TYPE].setWipable(); activeArcs[N_TYPE].setFactoryAngleIncrement(90); activeArcs[N_TYPE].setWidthOffset(12.0); /** General active arc */ active_arc = ArcProto.newInstance(this, "Active", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED) }); active_arc.setFunction(ArcProto.Function.DIFF); active_arc.setFactoryFixedAngle(true); active_arc.setWipable(); active_arc.setFactoryAngleIncrement(90); active_arc.setNotUsed(); //**************************************** NODES **************************************** /** metal-1-pin */ metalPinNodes[0] = PrimitiveNode.newInstance("Metal-1-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[0], new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[0].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[0].setArcsWipe(); metalPinNodes[0].setArcsShrink(); /** metal-2-pin */ metalPinNodes[1] = PrimitiveNode.newInstance("Metal-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[1], new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[1].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[1].setArcsWipe(); metalPinNodes[1].setArcsShrink(); /** metal-3-pin */ metalPinNodes[2] = PrimitiveNode.newInstance("Metal-3-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal3_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[2], new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[2].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[2].setArcsWipe(); metalPinNodes[2].setArcsShrink(); /** metal-4-pin */ metalPinNodes[3] = PrimitiveNode.newInstance("Metal-4-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal4_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[3], new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[3].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[3].setArcsWipe(); metalPinNodes[3].setArcsShrink(); /** metal-5-pin */ metalPinNodes[4] = PrimitiveNode.newInstance("Metal-5-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal5_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[4], new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[4].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[4].setArcsWipe(); metalPinNodes[4].setArcsShrink(); metalPinNodes[4].setNotUsed(); /** metal-6-pin */ metalPinNodes[5] = PrimitiveNode.newInstance("Metal-6-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal6_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[5].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[5], new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[5].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[5].setArcsWipe(); metalPinNodes[5].setArcsShrink(); metalPinNodes[5].setNotUsed(); /** polysilicon-1-pin */ poly1Pin_node = PrimitiveNode.newInstance("Polysilicon-1-Pin", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Pin_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Pin_node.setFunction(PrimitiveNode.Function.PIN); poly1Pin_node.setArcsWipe(); poly1Pin_node.setArcsShrink(); /** polysilicon-2-pin */ poly2Pin_node = PrimitiveNode.newInstance("Polysilicon-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Pin_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Pin_node.setFunction(PrimitiveNode.Function.PIN); poly2Pin_node.setArcsWipe(); poly2Pin_node.setArcsShrink(); poly2Pin_node.setNotUsed(); /** P-active-pin */ activePinNodes[P_TYPE] = PrimitiveNode.newInstance("P-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoNWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoPSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE]}, "p-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[P_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[P_TYPE].setArcsWipe(); activePinNodes[P_TYPE].setArcsShrink(); /** N-active-pin */ activePinNodes[N_TYPE] = PrimitiveNode.newInstance("N-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoPWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE]}, "n-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[N_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[N_TYPE].setArcsWipe(); activePinNodes[N_TYPE].setArcsShrink(); /** General active-pin */ activePin_node = PrimitiveNode.newInstance("Active-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activePin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePin_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); activePin_node.setFunction(PrimitiveNode.Function.PIN); activePin_node.setArcsWipe(); activePin_node.setArcsShrink(); activePin_node.setNotUsed(); /** metal-1-P-active-contact */ metalActiveContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX,Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "metal-1-p-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[P_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-N-active-contact */ metalActiveContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "metal-1-n-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[N_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-polysilicon-1-contact */ metal1Poly1Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-Con", this, 5.0, 5.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metal1Poly1Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly1Contact_node, new ArcProto[] {poly1_arc, metalArcs[0]}, "metal-1-polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2), EdgeV.fromBottom(2), EdgeH.fromRight(2), EdgeV.fromTop(2)) }); metal1Poly1Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly1Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly1Contact_node.setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metal1Poly1Contact_node.setMinSize(5, 5, "5.2, 7.3"); /** metal-1-polysilicon-2-contact */ metal1Poly2Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-2-Con", this, 10.0, 10.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); metal1Poly2Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly2Contact_node, new ArcProto[] {poly2_arc, metalArcs[0]}, "metal-1-polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4.5), EdgeV.fromBottom(4.5), EdgeH.fromRight(4.5), EdgeV.fromTop(4.5)) }); metal1Poly2Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly2Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly2Contact_node.setSpecialValues(new double [] {2, 2, 4, 4, 3, 3}); metal1Poly2Contact_node.setNotUsed(); metal1Poly2Contact_node.setMinSize(10, 10, "?"); /** metal-1-polysilicon-1-2-contact */ metal1Poly12Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-2-Con", this, 15.0, 15.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)) }); metal1Poly12Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly12Contact_node, new ArcProto[] {poly1_arc, poly2_arc, metalArcs[0]}, "metal-1-polysilicon-1-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7), EdgeV.fromBottom(7), EdgeH.fromRight(7), EdgeV.fromTop(7)) }); metal1Poly12Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly12Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly12Contact_node.setSpecialValues(new double [] {2, 2, 6.5, 6.5, 3, 3}); metal1Poly12Contact_node.setNotUsed(); metal1Poly12Contact_node.setMinSize(15, 15, "?"); /** P-Transistor */ /** N-Transistor */ String[] stdNames = {"p", "n"}; for (int i = 0; i < 2; i++) { transistorPolyLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyLLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyRLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyCLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorActiveLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveTLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveBLayers[i] = new Technology.NodeLayer(activeLayers[i], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10))}, 4, 4, 0, 0); transistorWellLayers[i] = new Technology.NodeLayer(wellLayers[(i+1)%transistorNodes.length], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); transistorSelectLayers[i] = new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(5)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(5))}, 6, 6, 2, 2); transistorNodes[i] = PrimitiveNode.newInstance(stdNames[i].toUpperCase()+"-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {transistorActiveLayers[i], transistorPolyLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {transistorActiveTLayers[i], transistorActiveBLayers[i], transistorPolyCLayers[i], transistorPolyLLayers[i], transistorPolyRLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); transistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); transistorNodes[i].setHoldsOutline(); transistorNodes[i].setCanShrink(); transistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); transistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); transistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); } /** Thick oxide transistors */ String[] thickNames = {"Thick-P", "Thick-N"}; Technology.NodeLayer[] thickActiveLayers = new Technology.NodeLayer[] {transistorActiveLayers[P_TYPE], transistorActiveLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLayers = new Technology.NodeLayer[] {transistorPolyLayers[P_TYPE], transistorPolyLayers[N_TYPE]}; Technology.NodeLayer[] thickWellLayers = new Technology.NodeLayer[] {transistorWellLayers[P_TYPE], transistorWellLayers[N_TYPE]}; Technology.NodeLayer[] thickSelectLayers = new Technology.NodeLayer[] {transistorSelectLayers[P_TYPE], transistorSelectLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveTLayers = new Technology.NodeLayer[] {transistorActiveTLayers[P_TYPE], transistorActiveTLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveBLayers = new Technology.NodeLayer[] {transistorActiveBLayers[P_TYPE], transistorActiveBLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyCLayers = new Technology.NodeLayer[] {transistorPolyCLayers[P_TYPE], transistorPolyCLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLLayers = new Technology.NodeLayer[] {transistorPolyLLayers[P_TYPE], transistorPolyLLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyRLayers = new Technology.NodeLayer[] {transistorPolyRLayers[P_TYPE], transistorPolyRLayers[N_TYPE]}; Technology.NodeLayer[] thickLayers = new Technology.NodeLayer[2]; for (int i = 0; i < thickLayers.length; i++) { thickLayers[i] = new Technology.NodeLayer(thickActive_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); } for (int i = 0; i < thickTransistorNodes.length; i++) { thickTransistorNodes[i] = PrimitiveNode.newInstance(thickNames[i] + "-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {thickActiveLayers[i], thickPolyLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {thickActiveTLayers[i], thickActiveBLayers[i], thickPolyCLayers[i], thickPolyLLayers[i], thickPolyRLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); thickTransistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); thickTransistorNodes[i].setHoldsOutline(); thickTransistorNodes[i].setCanShrink(); thickTransistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); thickTransistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); thickTransistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); thickTransistorNodes[i].setSpecialNode(); // For display purposes } /** Scalable-P-Transistor */ scalableTransistorNodes[P_TYPE] = PrimitiveNode.newInstance("P-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[P_TYPE].setFunction(PrimitiveNode.Function.TRAPMOS); scalableTransistorNodes[P_TYPE].setCanShrink(); scalableTransistorNodes[P_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** Scalable-N-Transistor */ scalableTransistorNodes[N_TYPE] = PrimitiveNode.newInstance("N-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[N_TYPE].setFunction(PrimitiveNode.Function.TRANMOS); scalableTransistorNodes[N_TYPE].setCanShrink(); scalableTransistorNodes[N_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** metal-1-metal-2-contact */ metalContactNodes[0] = PrimitiveNode.newInstance("Metal-1-Metal-2-Con", this, 5.0, 5.0, new SizeOffset(0.5, 0.5, 0.5, 0.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metalContactNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[0], new ArcProto[] {metalArcs[0], metalArcs[1]}, "metal-1-metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalContactNodes[0].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[0].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[0].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[0].setMinSize(5, 5, "8.3, 9.3"); /** metal-2-metal-3-contact */ metalContactNodes[1] = PrimitiveNode.newInstance("Metal-2-Metal-3-Con", this, 6.0, 6.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[1], new ArcProto[] {metalArcs[1], metalArcs[2]}, "metal-2-metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[1].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[1].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[1].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[1].setMinSize(6, 6, "14.3, 15.3"); /** metal-3-metal-4-contact */ metalContactNodes[2] = PrimitiveNode.newInstance("Metal-3-Metal-4-Con", this, 6.0, 6.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[2], new ArcProto[] {metalArcs[2], metalArcs[3]}, "metal-3-metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[2].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[2].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[2].setSpecialValues(new double [] {2, 2, 2, 2, 3, 3}); metalContactNodes[2].setMinSize(6, 6, "21.3, 22.3"); /** metal-4-metal-5-contact */ metalContactNodes[3] = PrimitiveNode.newInstance("Metal-4-Metal-5-Con", this, 7.0, 7.0, new SizeOffset(1.5, 1.5, 1.5, 1.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2.5)) }); metalContactNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[3], new ArcProto[] {metalArcs[3], metalArcs[4]}, "metal-4-metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[3].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[3].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[3].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[3].setNotUsed(); metalContactNodes[3].setMinSize(7, 7, "25.3, 26.3"); /** metal-5-metal-6-contact */ metalContactNodes[4] = PrimitiveNode.newInstance("Metal-5-Metal-6-Con", this, 8.0, 8.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)) }); metalContactNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[4], new ArcProto[] {metalArcs[4], metalArcs[5]}, "metal-5-metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[4].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[4].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[4].setSpecialValues(new double [] {3, 3, 2, 2, 4, 4}); metalContactNodes[4].setNotUsed(); metalContactNodes[4].setMinSize(8, 8, "29.3, 30.3"); /** Metal-1-P-Well Contact */ metalWellContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[P_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.WELL); metalWellContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[P_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /** Metal-1-N-Well Contact */ metalWellContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[N_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-substrate", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.SUBSTRATE); metalWellContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[N_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /********************** RPO Resistor-Node ********************************/ double polySelectOffX = 1.8; /* NP.C.3 */ // double rpoViaOffX = 2.2 /* RPO.C.2 */; double polyCutSize = 2.2; /* page 28 */ double resistorViaOff = 1.0; /* page 28 */ double resistorConW = polyCutSize + 2*resistorViaOff /*contact width viaW + 2*viaS = (2.2 + 2*1). It must be 1xN */; double resistorConH = resistorConW /*contact height*/; double resistorOffX = resistorConW + polySelectOffX + 1.2 /*0.22um-0.1 (poly extension in contact)*/; double resistorW = 20 + 2*resistorOffX; double resistorOffY = 2.2 /* RPO.C.2*/; double resistorH = 2*resistorOffY + resistorConH; // double resistorM1Off = 0.5 /*poly surround in poly contact */; // double resistorPolyOffX = 2.2; /* page 28 */ // double resistorV2OffX = -polyCutSize - 0.7 + resistorPolyX + resistorConW; // double resistorPortOffX = resistorPolyX + (resistorConW-polyCutSize)/2; // for the port double resistorM1Off = resistorViaOff - 0.6; // 0.6 = M.E.2 double resistorM1W = resistorConW-2*resistorM1Off; double resistorM1OffX = resistorM1Off + polySelectOffX; double resistorM1OffY = resistorM1Off + resistorOffY; double resistorV1OffX = resistorViaOff + polySelectOffX; double resistorV1OffY = resistorOffY + (resistorConH-polyCutSize)/2; rpoResistorNodes = new PrimitiveNode[2]; for (int i = 0; i < rpoResistorNodes.length; i++) { rpoResistorNodes[i] = PrimitiveNode.newInstance(stdNames[i]+"-Poly-RPO-Resistor", this, resistorW, resistorH, new SizeOffset(resistorOffX, resistorOffX, resistorOffY, resistorOffY), new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(polySelectOffX), EdgeV.fromBottom(resistorOffY)), new Technology.TechPoint(EdgeH.fromRight(polySelectOffX), EdgeV.fromTop(resistorOffY))}), new Technology.NodeLayer(silicideBlock_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorOffX), EdgeV.makeBottomEdge()), new Technology.TechPoint(EdgeH.fromRight(resistorOffX), EdgeV.makeTopEdge())}), new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(0.2)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(0.2))}), // Left contact new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX+resistorM1W), EdgeV.fromTop(resistorM1OffY))}), // left via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}), // Right contact new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX+resistorM1W), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX), EdgeV.fromTop(resistorM1OffY))}), // right via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}) }); rpoResistorNodes[i].addPrimitivePorts(new PrimitivePort [] { // left port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "left-rpo", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)), // right port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "right-rpo", 0,180, 1, PortCharacteristic.UNKNOWN, EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)) }); rpoResistorNodes[i].setFunction(PrimitiveNode.Function.PRESIST); rpoResistorNodes[i].setHoldsOutline(); rpoResistorNodes[i].setSpecialType(PrimitiveNode.POLYGONAL); } /** Metal-1-Node */ metal1Node_node = PrimitiveNode.newInstance("Metal-1-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Node_node, new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal1Node_node.setFunction(PrimitiveNode.Function.NODE); metal1Node_node.setHoldsOutline(); metal1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-2-Node */ metal2Node_node = PrimitiveNode.newInstance("Metal-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal2Node_node, new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal2Node_node.setFunction(PrimitiveNode.Function.NODE); metal2Node_node.setHoldsOutline(); metal2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-3-Node */ metal3Node_node = PrimitiveNode.newInstance("Metal-3-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal3Node_node, new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal3Node_node.setFunction(PrimitiveNode.Function.NODE); metal3Node_node.setHoldsOutline(); metal3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-4-Node */ metal4Node_node = PrimitiveNode.newInstance("Metal-4-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal4Node_node, new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal4Node_node.setFunction(PrimitiveNode.Function.NODE); metal4Node_node.setHoldsOutline(); metal4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-5-Node */ metal5Node_node = PrimitiveNode.newInstance("Metal-5-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal5Node_node, new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal5Node_node.setFunction(PrimitiveNode.Function.NODE); metal5Node_node.setHoldsOutline(); metal5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal5Node_node.setNotUsed(); /** Metal-6-Node */ metal6Node_node = PrimitiveNode.newInstance("Metal-6-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal6Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal6Node_node, new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal6Node_node.setFunction(PrimitiveNode.Function.NODE); metal6Node_node.setHoldsOutline(); metal6Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal6Node_node.setNotUsed(); /** Polysilicon-1-Node */ poly1Node_node = PrimitiveNode.newInstance("Polysilicon-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Node_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Node_node.setFunction(PrimitiveNode.Function.NODE); poly1Node_node.setHoldsOutline(); poly1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-2-Node */ poly2Node_node = PrimitiveNode.newInstance("Polysilicon-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Node_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Node_node.setFunction(PrimitiveNode.Function.NODE); poly2Node_node.setHoldsOutline(); poly2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); poly2Node_node.setNotUsed(); /** P-Active-Node */ pActiveNode_node = PrimitiveNode.newInstance("P-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); pActiveNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveNode_node.setHoldsOutline(); pActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Active-Node */ nActiveNode_node = PrimitiveNode.newInstance("N-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); nActiveNode_node.setFunction(PrimitiveNode.Function.NODE); nActiveNode_node.setHoldsOutline(); nActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Select-Node */ pSelectNode_node = PrimitiveNode.newInstance("P-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pSelectNode_node.setFunction(PrimitiveNode.Function.NODE); pSelectNode_node.setHoldsOutline(); pSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Select-Node */ nSelectNode_node = PrimitiveNode.newInstance("N-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); nSelectNode_node.setFunction(PrimitiveNode.Function.NODE); nSelectNode_node.setHoldsOutline(); nSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** PolyCut-Node */ polyCutNode_node = PrimitiveNode.newInstance("Poly-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCutNode_node, new ArcProto[0], "polycut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCutNode_node.setFunction(PrimitiveNode.Function.NODE); polyCutNode_node.setHoldsOutline(); polyCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** ActiveCut-Node */ activeCutNode_node = PrimitiveNode.newInstance("Active-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activeCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activeCutNode_node, new ArcProto[0], "activecut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); activeCutNode_node.setFunction(PrimitiveNode.Function.NODE); activeCutNode_node.setHoldsOutline(); activeCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-1-Node */ via1Node_node = PrimitiveNode.newInstance("Via-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via1Node_node, new ArcProto[0], "via-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via1Node_node.setFunction(PrimitiveNode.Function.NODE); via1Node_node.setHoldsOutline(); via1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-2-Node */ via2Node_node = PrimitiveNode.newInstance("Via-2-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via2Node_node, new ArcProto[0], "via-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via2Node_node.setFunction(PrimitiveNode.Function.NODE); via2Node_node.setHoldsOutline(); via2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-3-Node */ via3Node_node = PrimitiveNode.newInstance("Via-3-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via3Node_node, new ArcProto[0], "via-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via3Node_node.setFunction(PrimitiveNode.Function.NODE); via3Node_node.setHoldsOutline(); via3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-4-Node */ via4Node_node = PrimitiveNode.newInstance("Via-4-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via4Node_node, new ArcProto[0], "via-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via4Node_node.setFunction(PrimitiveNode.Function.NODE); via4Node_node.setHoldsOutline(); via4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via4Node_node.setNotUsed(); /** Via-5-Node */ via5Node_node = PrimitiveNode.newInstance("Via-5-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via5Node_node, new ArcProto[0], "via-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via5Node_node.setFunction(PrimitiveNode.Function.NODE); via5Node_node.setHoldsOutline(); via5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via5Node_node.setNotUsed(); /** P-Well-Node */ pWellNode_node = PrimitiveNode.newInstance("P-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); pWellNode_node.setFunction(PrimitiveNode.Function.NODE); pWellNode_node.setHoldsOutline(); pWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Well-Node */ nWellNode_node = PrimitiveNode.newInstance("N-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); nWellNode_node.setFunction(PrimitiveNode.Function.NODE); nWellNode_node.setHoldsOutline(); nWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Passivation-Node */ passivationNode_node = PrimitiveNode.newInstance("Passivation-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(passivation_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); passivationNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, passivationNode_node, new ArcProto[0], "passivation", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); passivationNode_node.setFunction(PrimitiveNode.Function.NODE); passivationNode_node.setHoldsOutline(); passivationNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Pad-Frame-Node */ padFrameNode_node = PrimitiveNode.newInstance("Pad-Frame-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(padFrame_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); padFrameNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, padFrameNode_node, new ArcProto[0], "pad-frame", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); padFrameNode_node.setFunction(PrimitiveNode.Function.NODE); padFrameNode_node.setHoldsOutline(); padFrameNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Poly-Cap-Node */ polyCapNode_node = PrimitiveNode.newInstance("Poly-Cap-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCap_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCapNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCapNode_node, new ArcProto[0], "poly-cap", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCapNode_node.setFunction(PrimitiveNode.Function.NODE); polyCapNode_node.setHoldsOutline(); polyCapNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Active-Well-Node */ pActiveWellNode_node = PrimitiveNode.newInstance("P-Active-Well-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveWellNode_node, new ArcProto[0], "p-active-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pActiveWellNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveWellNode_node.setHoldsOutline(); pActiveWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-1-Transistor-Node */ polyTransistorNode_node = PrimitiveNode.newInstance("Transistor-Poly-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyTransistorNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyTransistorNode_node, new ArcProto[] {poly1_arc}, "trans-poly-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); polyTransistorNode_node.setFunction(PrimitiveNode.Function.NODE); polyTransistorNode_node.setHoldsOutline(); polyTransistorNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Silicide-Block-Node */ silicideBlockNode_node = PrimitiveNode.newInstance("Silicide-Block-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(silicideBlock_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); silicideBlockNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, silicideBlockNode_node, new ArcProto[] {poly1_arc}, "silicide-block", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); silicideBlockNode_node.setFunction(PrimitiveNode.Function.NODE); silicideBlockNode_node.setHoldsOutline(); silicideBlockNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Thick-Active-Node */ thickActiveNode_node = PrimitiveNode.newInstance("Thick-Active-Node", this, 4.0, 4.0, null, // 4.0 is given by rule 24.1 new Technology.NodeLayer [] { new Technology.NodeLayer(thickActive_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); thickActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickActiveNode_node, new ArcProto[] {poly1_arc}, "thick-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); thickActiveNode_node.setFunction(PrimitiveNode.Function.NODE); thickActiveNode_node.setHoldsOutline(); thickActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); // The pure layer nodes metalLayers[0].setPureLayerNode(metal1Node_node); // Metal-1 metalLayers[1].setPureLayerNode(metal2Node_node); // Metal-2 metalLayers[2].setPureLayerNode(metal3Node_node); // Metal-3 metalLayers[3].setPureLayerNode(metal4Node_node); // Metal-4 metalLayers[4].setPureLayerNode(metal5Node_node); // Metal-5 metalLayers[5].setPureLayerNode(metal6Node_node); // Metal-6 poly1_lay.setPureLayerNode(poly1Node_node); // Polysilicon-1 poly2_lay.setPureLayerNode(poly2Node_node); // Polysilicon-2 activeLayers[P_TYPE].setPureLayerNode(pActiveNode_node); // P-Active activeLayers[N_TYPE].setPureLayerNode(nActiveNode_node); // N-Active selectLayers[P_TYPE].setPureLayerNode(pSelectNode_node); // P-Select selectLayers[N_TYPE].setPureLayerNode(nSelectNode_node); // N-Select wellLayers[P_TYPE].setPureLayerNode(pWellNode_node); // P-Well wellLayers[N_TYPE].setPureLayerNode(nWellNode_node); // N-Well polyCutLayer.setPureLayerNode(polyCutNode_node); // Poly-Cut activeCut_lay.setPureLayerNode(activeCutNode_node); // Active-Cut via1_lay.setPureLayerNode(via1Node_node); // Via-1 via2_lay.setPureLayerNode(via2Node_node); // Via-2 via3_lay.setPureLayerNode(via3Node_node); // Via-3 via4_lay.setPureLayerNode(via4Node_node); // Via-4 via5_lay.setPureLayerNode(via5Node_node); // Via-5 passivation_lay.setPureLayerNode(passivationNode_node); // Passivation transistorPoly_lay.setPureLayerNode(polyTransistorNode_node); // Transistor-Poly polyCap_lay.setPureLayerNode(polyCapNode_node); // Poly-Cap pActiveWell_lay.setPureLayerNode(pActiveWellNode_node); // P-Active-Well silicideBlock_lay.setPureLayerNode(silicideBlockNode_node); // Silicide-Block thickActive_lay.setPureLayerNode(thickActiveNode_node); // Thick-Active padFrame_lay.setPureLayerNode(padFrameNode_node); // Pad-Frame // Information for palette int maxY = metalArcs.length + activeArcs.length + 1 /* poly*/ + 1 /* trans */ + 1 /*misc*/ + 1 /* well */; nodeGroups = new Object[maxY][3]; int count = 0; String[] shortNames = {"p", "n"}; List tmp; // Transistor nodes first for (int i = 0; i < transistorNodes.length; i++) { tmp = new ArrayList(2); String tmpVar = shortNames[i]+"Mos"; tmp.add(makeNodeInst(transistorNodes[i], transistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(thickTransistorNodes[i], thickTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(scalableTransistorNodes[i], scalableTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); nodeGroups[count][i+1] = tmp; } // Well second count++; for (int i = 0; i < metalWellContactNodes.length; i++) { String tmpVar = shortNames[i]+"Well"; nodeGroups[count][i+1] = makeNodeInst(metalWellContactNodes[i], metalWellContactNodes[i].getFunction(), 0, true, tmpVar, 5.5); } // RPO resistors for (int i = 0; i < rpoResistorNodes.length; i++) { String tmpVar = shortNames[i]+"R"; tmp = new ArrayList(1); tmp.add(makeNodeInst(rpoResistorNodes[i], rpoResistorNodes[i].getFunction(), 0, true, tmpVar, 10)); nodeGroups[i][0] = tmp; } // Active/Well first for (int i = 0; i < activeArcs.length; i++) { nodeGroups[++count][0] = activeArcs[i]; nodeGroups[count][1] = activePinNodes[i]; String tmpVar = shortNames[i]+"Act"; nodeGroups[count][2] = makeNodeInst(metalActiveContactNodes[i], metalActiveContactNodes[i].getFunction(), 0, true, tmpVar, 5.55); } // Poly-related node insts nodeGroups[++count][0] = poly1_arc; nodeGroups[count][1] = poly1Pin_node; nodeGroups[count][2] = metal1Poly1Contact_node; // MXMY contacts for (int i = 0; i < metalArcs.length; i++) { nodeGroups[++count][0] = metalArcs[i]; nodeGroups[count][1] = metalPinNodes[i]; nodeGroups[count][2] = (i < metalArcs.length - 1) ? metalContactNodes[i] : null; } // On the side nodeGroups[++count][0] = "Pure"; nodeGroups[count][1] = "Misc."; nodeGroups[count][2] = "Cell"; } private void resizeNodes() { String foundry = getSelectedFoundry(); if (foundry.equals(Foundry.TSMC_FOUNDRY)) { // Poly contacts Technology.NodeLayer node = metal1Poly1Contact_node.getLayers()[2]; // Cut node.setPoints(Technology.TechPoint.makeIndented(1.4)); metal1Poly1Contact_node.setSpecialValues(new double [] {2.2, 2.2, 1.4, 1.4, 2.8, 2.8}); // 2.8 for 1xN and NxN cuts (CO.S.2). // Active contacts for (int i = 0; i < metalActiveContactNodes.length; i++) { node = metalActiveContactNodes[i].getLayers()[4]; // Cut node.setPoints(Technology.TechPoint.makeIndented(7.4)); node = metalActiveContactNodes[i].getLayers()[3]; // Select node.setPoints(Technology.TechPoint.makeIndented(3.4)); // so it is 2.6 with respect to active metalActiveContactNodes[i].setSpecialValues(new double [] {2.2, 2.2, 1.4, 1.4, 2.8, 2.8}); } // Well contacts for (int i = 0; i < metalWellContactNodes.length; i++) { node = metalWellContactNodes[i].getLayers()[4]; // Cut node.setPoints(Technology.TechPoint.makeIndented(7.4)); node = metalWellContactNodes[i].getLayers()[2]; // Well 3 is not guarantee during construction! node.setPoints(Technology.TechPoint.makeIndented(3)); metalWellContactNodes[i].setSpecialValues(new double [] {2.2, 2.2, 1.4, 1.4, 2.8, 2.8}); // to have 4.3 between well and active NP.E.4 } // Via1 -> Via4 double [] indentValues = {1.2, 1.7, 1.7, 2.2, 2.7}; double [] cutValues = {0.6, 0.6, 0.6, 0.6, 0.9}; // 0.6 (VIAX.E.2) 0.9 VIA5.E.1 double [] sizeValues = {2.6, 2.6, 2.6, 2.6, 3.6}; // 2.6 (VIAxS.1) double [] spaceValues = {2.6, 2.6, 2.6, 2.6, 3.6}; // it should be 3.5 instead of 3.6 but even number kept for symmetry for (int i = 0; i < metalContactNodes.length; i++) { node = metalContactNodes[i].getLayers()[2]; node.setPoints(Technology.TechPoint.makeIndented(indentValues[i])); metalContactNodes[i].setSpecialValues(new double [] {sizeValues[i], sizeValues[i], cutValues[i], cutValues[i], spaceValues[i], spaceValues[i]}); } // Transistors /* Poly -> 3.2 top/bottom extension */ for (int i = 0; i < 2; i++) { transistorWellLayers[i].getLeftEdge().setAdder(1.7); transistorWellLayers[i].getRightEdge().setAdder(-1.7); transistorSelectLayers[i].getLeftEdge().setAdder(2.4); transistorSelectLayers[i].getRightEdge().setAdder(-2.4); // 2.5 // Poly X values transistorPolyLayers[i].getLeftEdge().setAdder(3.8); transistorPolyLayers[i].getRightEdge().setAdder(-3.8); transistorPolyLLayers[i].getLeftEdge().setAdder(3.8); transistorPolyRLayers[i].getRightEdge().setAdder(-3.8); // Poly Y values transistorPolyLayers[i].getBottomEdge().setAdder(10.1); transistorPolyLayers[i].getTopEdge().setAdder(-10.1); transistorPolyLLayers[i].getBottomEdge().setAdder(10.1); transistorPolyLLayers[i].getTopEdge().setAdder(-10.1); transistorPolyRLayers[i].getBottomEdge().setAdder(10.1); transistorPolyRLayers[i].getTopEdge().setAdder(-10.1); transistorPolyCLayers[i].getBottomEdge().setAdder(10.1); transistorPolyCLayers[i].getTopEdge().setAdder(-10.1); transistorActiveLayers[i].getBottomEdge().setAdder(6.9); transistorActiveLayers[i].getTopEdge().setAdder(-6.9); transistorActiveBLayers[i].getBottomEdge().setAdder(6.9); transistorActiveBLayers[i].getTopEdge().setAdder(10.1); transistorActiveTLayers[i].getTopEdge().setAdder(-6.9); transistorActiveTLayers[i].getBottomEdge().setAdder(-10.1); transistorNodes[i].setSizeOffset(new SizeOffset(6, 6, 10.1, 10.1)); // PrimitivePort port = transistorNodes[i].getPort(0).getBasePort(); // // trans-poly-left // port.getLeft().setAdder(4.2); // port.getRight().setAdder(4.2); // // trans-poly-right // port = transistorNodes[i].getPort(2).getBasePort(); // port.getLeft().setAdder(-4.2); // port.getRight().setAdder(-4.2); } // Channel length 1.8 poly1_arc.setDefaultWidth(1.8); poly1Pin_node.setDefSize(1.8, 1.8); // Metal 6 arc width 4.4 metalArcs[5].setDefaultWidth(5); } else // Mosis { Technology.NodeLayer node = metal1Poly1Contact_node.getLayers()[2]; // Cut node.setPoints(Technology.TechPoint.makeIndented(1.5)); metal1Poly1Contact_node.setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); // Active contacts for (int i = 0; i < metalActiveContactNodes.length; i++) { node = metalActiveContactNodes[i].getLayers()[4]; // Cut node.setPoints(Technology.TechPoint.makeIndented(7.5)); node = metalActiveContactNodes[i].getLayers()[3]; // Select node.setPoints(Technology.TechPoint.makeIndented(4)); // back to Mosis default=4 metalActiveContactNodes[i].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); } // Well contacts for (int i = 0; i < metalWellContactNodes.length; i++) { node = metalWellContactNodes[i].getLayers()[4]; // Cut node.setPoints(Technology.TechPoint.makeIndented(7.5)); metalWellContactNodes[i].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); node = metalWellContactNodes[i].getLayers()[2]; // Well node.setPoints(Technology.TechPoint.makeIndented(3)); } // Via1 -> Via4. Some values depend on original node size double [] indentValues = {1.5, 2, 2, 2.5, 3}; double [] cutValues = {1, 1, 2, 1, 2}; double [] sizeValues = {2, 2, 2, 2, 3}; double [] spaceValues = {3, 3, 3, 3, 4}; for (int i = 0; i < 4; i++) { node = metalContactNodes[i].getLayers()[2]; node.setPoints(Technology.TechPoint.makeIndented(indentValues[i])); metalContactNodes[i].setSpecialValues(new double [] {sizeValues[i], sizeValues[i], cutValues[i], cutValues[i], spaceValues[i], spaceValues[i]}); } // Transistors /* Poly -> 3.2 top/bottom extension */ for (int i = 0; i < 2; i++) { transistorWellLayers[i].getLeftEdge().setAdder(0); transistorWellLayers[i].getRightEdge().setAdder(0); transistorSelectLayers[i].getLeftEdge().setAdder(4); transistorSelectLayers[i].getRightEdge().setAdder(-4); transistorPolyLayers[i].getLeftEdge().setAdder(4); transistorPolyLayers[i].getRightEdge().setAdder(-4); transistorPolyLLayers[i].getLeftEdge().setAdder(4); transistorPolyRLayers[i].getRightEdge().setAdder(-4); transistorPolyLayers[i].getBottomEdge().setAdder(10); transistorPolyLayers[i].getTopEdge().setAdder(-10); transistorPolyLLayers[i].getBottomEdge().setAdder(10); transistorPolyLLayers[i].getTopEdge().setAdder(-10); transistorPolyRLayers[i].getBottomEdge().setAdder(10); transistorPolyRLayers[i].getTopEdge().setAdder(-10); transistorPolyCLayers[i].getBottomEdge().setAdder(10); transistorPolyCLayers[i].getTopEdge().setAdder(-10); transistorActiveLayers[i].getBottomEdge().setAdder(7); transistorActiveLayers[i].getTopEdge().setAdder(-7); transistorActiveBLayers[i].getBottomEdge().setAdder(7); transistorActiveBLayers[i].getTopEdge().setAdder(10); transistorActiveTLayers[i].getTopEdge().setAdder(-7); transistorActiveTLayers[i].getBottomEdge().setAdder(-10); transistorNodes[i].setSizeOffset(new SizeOffset(6, 6, 10, 10)); // PrimitivePort port = transistorNodes[i].getPort(0).getBasePort(); // // trans-poly-left // port.getLeft().setAdder(4); // port.getRight().setAdder(4); // // trans-poly-right // port = transistorNodes[i].getPort(2).getBasePort(); // port.getLeft().setAdder(-4); // port.getRight().setAdder(-4); } // Channel length 2 poly1_arc.setDefaultWidth(2.0); poly1Pin_node.setDefSize(2, 2); // Metal 6 arc width 4. Original value metalArcs[5].setDefaultWidth(4); } } /** * Reset default width values. In 180nm the poly arcs are resized to default values * @param cell */ public void resetDefaultValues(Cell cell) { // for (Iterator itNod = cell.getNodes(); itNod.hasNext(); ) // { // NodeInst ni = (NodeInst)itNod.next(); // // Only valid for transistors in layout so VarContext=null is OK // TransistorSize size = ni.getTransistorSize(null); // if (size != null) // { // double length = size.getDoubleLength(); // int mult = (int)(length / poly1_arc.getWidth()); // if (mult < 1) // System.out.println("Problems resizing transistor lengths"); // double newLen = poly1_arc.getWidth() * mult; // if (!DBMath.areEquals(newLen,length)) // { // // Making wires from top/bottom ports fixed-angle otherwise they get twisted. // PortInst pi = ni.getPortInst(1); // List list = new ArrayList(2); // // Not sure how many connections are so fix angles to all // for (Iterator it = pi.getConnections(); it.hasNext();) // { // Connection c = (Connection)it.next(); // c.getArc().setFixedAngle(true); // list.add(c.getArc()); // } // pi = ni.getPortInst(3); // // Not sure how many connections are so fix angles to all // for (Iterator it = pi.getConnections(); it.hasNext();) // { // Connection c = (Connection)it.next(); // c.getArc().setFixedAngle(true); // list.add(c.getArc()); // } //// ni.setPrimitiveNodeSize(size.getDoubleWidth(), newLen); //// for (int i = 0; i < list.size(); i++) //// { //// ArcInst arc = (ArcInst)list.get(i); ////// arc.setFixedAngle(false); //// } // } // } // } for(Iterator itArc = cell.getArcs(); itArc.hasNext(); ) { ArcInst ai = (ArcInst)itArc.next(); boolean found = false; double maxLen = -Double.MIN_VALUE; // Guessing arc thickness based on connections // Default doesn't work in existing cells // Valid for poly layers and M6 only! // Metal 6 because the min M6 changed in Mosis if (!(ai.getProto().getFunction().isPoly() /*|| ai.getProto().getFunction() == ArcProto.Function.METAL6)*/)) continue; for(int i=0; i<2; i++) { Connection thisCon = ai.getConnection(i); NodeInst ni = thisCon.getPortInst().getNodeInst(); // covers transistors and resistors PrimitiveNodeSize size = ni.getPrimitiveNodeSize(null); // This is only for layout if (size != null) { double length = size.getDoubleLength(); if (!DBMath.areEquals(length, ai.getWidth())) // if (DBMath.isGreaterThan(length, maxLen)) { maxLen = length; found = true; ai.modify(maxLen - ai.getWidth(), 0, 0, 0, 0); break; } } } // // No transistor or resistor found // if (!found) // { // maxLen = ai.getProto().getDefaultWidth(); // found = (!DBMath.areEquals(ai.getWidth(), maxLen)); // default must be applied // } // if (found) // { // ai.modify(maxLen - ai.getWidth(), 0, 0, 0, 0); // } } } /******************** SUPPORT METHODS ********************/ /** * Method to set the technology to state "newstate", which encodes the number of metal * layers, whether it is a deep process, and other rules. */ public void setState() { // set rules cachedRules = getFactoryDesignRules(); // disable Metal-3/4/5/6-Pin, Metal-2/3/4/5-Metal-3/4/5/6-Con, Metal-3/4/5/6-Node, Via-2/3/4/5-Node metalPinNodes[2].setNotUsed(); metalPinNodes[3].setNotUsed(); metalPinNodes[4].setNotUsed(); metalPinNodes[5].setNotUsed(); metalContactNodes[1].setNotUsed(); metalContactNodes[2].setNotUsed(); metalContactNodes[3].setNotUsed(); metalContactNodes[4].setNotUsed(); metal3Node_node.setNotUsed(); metal4Node_node.setNotUsed(); metal5Node_node.setNotUsed(); metal6Node_node.setNotUsed(); via2Node_node.setNotUsed(); via3Node_node.setNotUsed(); via4Node_node.setNotUsed(); via5Node_node.setNotUsed(); // disable Polysilicon-2 poly2_arc.setNotUsed(); poly2Pin_node.setNotUsed(); metal1Poly2Contact_node.setNotUsed(); metal1Poly12Contact_node.setNotUsed(); poly2Node_node.setNotUsed(); // disable metal 3-6 arcs metalArcs[2].setNotUsed(); metalArcs[3].setNotUsed(); metalArcs[4].setNotUsed(); metalArcs[5].setNotUsed(); // enable the desired nodes switch (getNumMetal()) { case 6: metalPinNodes[5].clearNotUsed(); metalContactNodes[4].clearNotUsed(); metal6Node_node.clearNotUsed(); via5Node_node.clearNotUsed(); metalArcs[5].clearNotUsed(); // FALLTHROUGH case 5: metalPinNodes[4].clearNotUsed(); metalContactNodes[3].clearNotUsed(); metal5Node_node.clearNotUsed(); via4Node_node.clearNotUsed(); metalArcs[4].clearNotUsed(); // FALLTHROUGH case 4: metalPinNodes[3].clearNotUsed(); metalContactNodes[2].clearNotUsed(); metal4Node_node.clearNotUsed(); via3Node_node.clearNotUsed(); metalArcs[3].clearNotUsed(); // FALLTHROUGH case 3: metalPinNodes[2].clearNotUsed(); metalContactNodes[1].clearNotUsed(); metal3Node_node.clearNotUsed(); via2Node_node.clearNotUsed(); metalArcs[2].clearNotUsed(); break; } if (getRuleSet() != DEEPRULES) { if (isSecondPolysilicon()) { // non-DEEP: enable Polysilicon-2 poly2_arc.clearNotUsed(); poly2Pin_node.clearNotUsed(); metal1Poly2Contact_node.clearNotUsed(); metal1Poly12Contact_node.clearNotUsed(); poly2Node_node.clearNotUsed(); } } // now rewrite the description setTechDesc(describeState()); } /** * Method to describe the technology when it is in state "state". */ private String describeState() { int numMetals = getNumMetal(); String rules = ""; switch (getRuleSet()) { case SCMOSRULES: rules = "now standard"; break; case DEEPRULES: rules = "now deep"; break; case SUBMRULES: rules = "now submicron"; break; } int numPolys = 1; if (isSecondPolysilicon()) numPolys = 2; String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " + numPolys + "], flex rules [" + rules + "]"; if (isDisallowStackedVias()) description += ", stacked vias disallowed"; if (isAlternateActivePolyRules()) description += ", alternate contact rules"; return description + ")"; } /******************** SCALABLE TRANSISTOR DESCRIPTION ********************/ private static final int SCALABLE_ACTIVE_TOP = 0; private static final int SCALABLE_METAL_TOP = 1; private static final int SCALABLE_ACTIVE_BOT = 2; private static final int SCALABLE_METAL_BOT = 3; private static final int SCALABLE_ACTIVE_CTR = 4; private static final int SCALABLE_POLY = 5; private static final int SCALABLE_WELL = 6; private static final int SCALABLE_SUBSTRATE = 7; private static final int SCALABLE_TOTAL = 8; /** * Method to return a list of Polys that describe a given NodeInst. * This method overrides the general one in the Technology object * because of the unusual primitives in this Technology. * @param ni the NodeInst to describe. * @param wnd the window in which this node will be drawn. * @param context the VarContext to this node in the hierarchy. * @param electrical true to get the "electrical" layers. * This makes no sense for Schematics primitives. * @param reasonable true to get only a minimal set of contact cuts in large contacts. * This makes no sense for Schematics primitives. * @param primLayers an array of NodeLayer objects to convert to Poly objects. * @param layerOverride the layer to use for all generated polygons (if not null). * @return an array of Poly objects. */ public Poly [] getShapeOfNode(NodeInst ni, EditWindow wnd, VarContext context, boolean electrical, boolean reasonable, Technology.NodeLayer [] primLayers, Layer layerOverride) { NodeProto prototype = ni.getProto(); if (prototype == scalableTransistorNodes[P_TYPE] || prototype == scalableTransistorNodes[N_TYPE]) return getShapeOfNodeScalable(ni, wnd, context, reasonable); else if (prototype == rpoResistorNodes[P_TYPE] || prototype == rpoResistorNodes[N_TYPE]) return getShapeOfNodeResistor(ni, wnd, context, electrical, reasonable); // Default return super.getShapeOfNode(ni, wnd, context, electrical, reasonable, primLayers, layerOverride); } /** * Special getShapeOfNode function for RPO poly resistors * @param ni * @param wnd * @param context * @param electrical * @param reasonable * @return */ private Poly [] getShapeOfNodeResistor(NodeInst ni, EditWindow wnd, VarContext context, boolean electrical, boolean reasonable) { // now compute the number of polygons PrimitiveNode np = (PrimitiveNode)ni.getProto(); Technology.NodeLayer [] layers = np.getLayers(); EdgeV polyV = null; EdgeH polyH = null, rpoH = null; // Number of cuts only varies along Y for (int i = 0; i < layers.length; i++) { TechPoint [] points = layers[i].getPoints(); if (layers[i].getLayer().getFunction() == Layer.Function.POLY1) // found the poly layer { polyH = points[1].getX(); polyV = points[1].getY(); } else if (layers[i].getLayer().getFunction() == Layer.Function.ART) // RPO is defined as ART { rpoH = points[0].getX(); } } if (polyV == null || polyH == null || rpoH == null) throw new Error("Error finding poly/rpo layers in " + rpoResistorNodes); double polyOffX = Math.abs(polyH.getAdder()); double polyOffY = Math.abs(polyV.getAdder()); double polyConX = 4.2; // 2.2 (via) + 2 * 1. GPage 28 // same offset as in poly contact, // SizeOffset is zero for that primitive and special values are calculated from external boundary MultiCutData cutData = new MultiCutData(polyConX, ni.getYSize() - 2*polyOffY, 0, 0, 0, 0, 0, 0, metal1Poly1Contact_node.getSpecialValues()); if (cutData.numCutsX() != 1) throw new Error("Error: onw cut should be the only value"); Technology.NodeLayer [] newNodeLayers = layers; List list = new ArrayList(layers.length); Technology.NodeLayer cutTemplate = null; // Copy layers that are not poly cuts for (int i = 0; i < layers.length; i++) { if (layers[i].getLayer().getFunction() == Layer.Function.CONTACT1) // found the poly layer { cutTemplate = layers[i]; continue; } list.add(new Technology.NodeLayer(layers[i])); } if (cutTemplate == null) throw new Error("No cut template found for " + rpoResistorNodes); // creating the cuts now double anchorX = polyConX/2; double anchorY = (ni.getYSize() - 2*polyOffY)/2; for (int i = 0; i < cutData.numCuts(); i++) { Poly poly = cutData.fillCutPoly(0, 0, i); Rectangle2D rect = poly.getBounds2D(); double offsetX = anchorX+rect.getMinX()+polyOffX; double offsetY = anchorY+rect.getMinY()+polyOffY; // left cuts Technology.NodeLayer cut = new Technology.NodeLayer(cutTemplate); TechPoint [] points = cut.getPoints(); points[0] = new Technology.TechPoint(EdgeH.fromLeft(offsetX), EdgeV.fromBottom(offsetY)); points[1] = new Technology.TechPoint(EdgeH.fromLeft(offsetX+cutData.getCutSizeX()), EdgeV.fromBottom(offsetY+cutData.getCutSizeY())); list.add(cut); //right cuts cut = new Technology.NodeLayer(cutTemplate); points = cut.getPoints(); points[0] = new Technology.TechPoint(EdgeH.fromRight(offsetX), EdgeV.fromBottom(offsetY)); points[1] = new Technology.TechPoint(EdgeH.fromRight(offsetX+cutData.getCutSizeX()), EdgeV.fromBottom(offsetY+cutData.getCutSizeY())); list.add(cut); } newNodeLayers = new Technology.NodeLayer[list.size()]; System.arraycopy(list.toArray(), 0, newNodeLayers, 0, list.size()); // now let the superclass convert it to Polys return super.getShapeOfNode(ni, wnd, context, electrical, reasonable, newNodeLayers, null); } /** * Special getShapeOfNode function for scalable transistors * @param ni * @param wnd * @param context * @param reasonable * @return */ private Poly [] getShapeOfNodeScalable(NodeInst ni, EditWindow wnd, VarContext context, boolean reasonable) { // determine special configurations (number of active contacts, inset of active contacts) int numContacts = 2; boolean insetContacts = false; Variable var = ni.getVar(TRANS_CONTACT, String.class); if (var != null) { String pt = (String)var.getObject(); for(int i=0; i<pt.length(); i++) { char chr = pt.charAt(i); if (chr == '0' || chr == '1' || chr == '2') { numContacts = chr - '0'; } else if (chr == 'i' || chr == 'I') insetContacts = true; } } int boxOffset = 4 - numContacts * 2; // determine width PrimitiveNode np = (PrimitiveNode)ni.getProto(); double nodeWid = ni.getXSize(); double activeWid = nodeWid - 14; int extraInset = 0; var = ni.getVar(Schematics.ATTR_WIDTH); if (var != null) { VarContext evalContext = context; if (evalContext == null) evalContext = VarContext.globalContext; String extra = var.describe(evalContext, ni); try { Object o = evalContext.evalVarRecurse(var, ni); if (o != null) extra = o.toString(); } catch (VarContext.EvalException e) {} double requestedWid = TextUtils.atof(extra); if (requestedWid > activeWid) { System.out.println("Warning: " + ni.getParent() + ", " + ni + " requests width of " + requestedWid + " but is only " + activeWid + " wide"); } if (requestedWid < activeWid && requestedWid > 0) { extraInset = (int)((activeWid - requestedWid) / 2); activeWid = requestedWid; } } double actInset = (nodeWid-activeWid) / 2; double polyInset = actInset - 2; double actContInset = 7 + extraInset; // contacts must be 5 wide at a minimum if (activeWid < 5) actContInset -= (5-activeWid)/2; double metContInset = actContInset + 0.5; // determine the multicut information double [] specialValues = metalActiveContactNodes[P_TYPE].getSpecialValues(); double cutSize = specialValues[0]; double cutIndent = specialValues[2]; // or specialValues[3] double cutSep = specialValues[4]; // or specialValues[5] int numCuts = (int)((activeWid-cutIndent*2+cutSep) / (cutSize+cutSep)); if (numCuts <= 0) numCuts = 1; double cutBase = 0; if (numCuts != 1) cutBase = (activeWid-cutIndent*2 - cutSize*numCuts - cutSep*(numCuts-1)) / 2 + (nodeWid-activeWid)/2 + cutIndent; // now compute the number of polygons int extraCuts = numCuts*2 - (2-numContacts) * numCuts; Technology.NodeLayer [] layers = np.getLayers(); int count = SCALABLE_TOTAL + extraCuts - boxOffset; Technology.NodeLayer [] newNodeLayers = new Technology.NodeLayer[count]; // load the basic layers int fillIndex = 0; for(int box = boxOffset; box < SCALABLE_TOTAL; box++) { TechPoint [] oldPoints = layers[box].getPoints(); TechPoint [] points = new TechPoint[oldPoints.length]; for(int i=0; i<oldPoints.length; i++) points[i] = oldPoints[i].duplicate(); switch (box) { case SCALABLE_ACTIVE_CTR: // active that passes through gate points[0].getX().setAdder(actInset); points[0].getX().setAdder(actInset); points[1].getX().setAdder(-actInset); break; case SCALABLE_ACTIVE_TOP: // active surrounding contacts case SCALABLE_ACTIVE_BOT: points[0].getX().setAdder(actContInset); points[1].getX().setAdder(-actContInset); if (insetContacts) { double shift = 0.5; if (points[0].getY().getAdder() < 0) shift = -0.5; points[0].getY().setAdder(points[0].getY().getAdder() + shift); points[1].getY().setAdder(points[1].getY().getAdder() + shift); } break; case SCALABLE_POLY: // poly points[0].getX().setAdder(polyInset); points[1].getX().setAdder(-polyInset); break; case SCALABLE_METAL_TOP: // metal surrounding contacts case SCALABLE_METAL_BOT: points[0].getX().setAdder(metContInset); points[1].getX().setAdder(-metContInset); if (insetContacts) { double shift = 0.5; if (points[0].getY().getAdder() < 0) shift = -0.5; points[0].getY().setAdder(points[0].getY().getAdder() + shift); points[1].getY().setAdder(points[1].getY().getAdder() + shift); } break; case SCALABLE_WELL: // well and select case SCALABLE_SUBSTRATE: if (insetContacts) { points[0].getY().setAdder(points[0].getY().getAdder() + 0.5); points[1].getY().setAdder(points[1].getY().getAdder() - 0.5); } break; } newNodeLayers[fillIndex] = new Technology.NodeLayer(layers[box].getLayer(), layers[box].getPortNum(), layers[box].getStyle(), layers[box].getRepresentation(), points); fillIndex++; } // load the contact cuts for(int box = 0; box < extraCuts; box++) { int oldIndex = SCALABLE_TOTAL; if (box >= numCuts) oldIndex++; // make a new description of this layer TechPoint [] oldPoints = layers[oldIndex].getPoints(); TechPoint [] points = new TechPoint[oldPoints.length]; for(int i=0; i<oldPoints.length; i++) points[i] = oldPoints[i].duplicate(); if (numCuts == 1) { points[0].getX().setAdder(ni.getXSize() / 2 - cutSize/2); points[1].getX().setAdder(ni.getXSize() / 2 + cutSize/2); } else { int cut = box % numCuts; double base = cutBase + cut * (cutSize + cutSep); points[0].getX().setAdder(base); points[1].getX().setAdder(base + cutSize); } if (insetContacts) { double shift = 0.5; if (points[0].getY().getAdder() < 0) shift = -0.5; points[0].getY().setAdder(points[0].getY().getAdder() + shift); points[1].getY().setAdder(points[1].getY().getAdder() + shift); } newNodeLayers[fillIndex] = new Technology.NodeLayer(layers[oldIndex].getLayer(), layers[oldIndex].getPortNum(), layers[oldIndex].getStyle(), layers[oldIndex].getRepresentation(), points); fillIndex++; } // now let the superclass convert it to Polys return super.getShapeOfNode(ni, wnd, context, false, reasonable, newNodeLayers, null); } /******************** PARAMETERIZABLE DESIGN RULES ********************/ /** * Method to build "factory" design rules, given the current technology settings. * @return the "factory" design rules for this Technology. * Returns null if there is an error loading the rules. */ public DRCRules getFactoryDesignRules() { MOSRules rules = new MOSRules(this); // doesn't load rules that int foundryMode = getFoundry(); // Resize primitives according to the foundry resizeNodes(); // load the DRC tables from the explanation table rules.wideLimit = new Double(WIDELIMIT); for(int pass=0; pass<2; pass++) { for(int i=0; i < theRules.length; i++) { // see if the rule applies if (pass == 0) { if (theRules[i].ruleType == DRCTemplate.NODSIZ) continue; } else { if (theRules[i].ruleType != DRCTemplate.NODSIZ) continue; } int when = theRules[i].when; if (when != DRCTemplate.ALL) { // One of the 2 is present. Absence means rule is valid for both if ((when&DRCTemplate.MOSIS) != 0 && foundryMode == DRCTemplate.TSMC) continue; else if ((when&DRCTemplate.TSMC) != 0 && foundryMode == DRCTemplate.MOSIS) continue; // skipping this rule } boolean goodrule = true; if ((when&(DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.SC)) != 0) { switch (getRuleSet()) { case DEEPRULES: if ((when&DRCTemplate.DE) == 0) goodrule = false; break; case SUBMRULES: if ((when&DRCTemplate.SU) == 0) goodrule = false; break; case SCMOSRULES: if ((when&DRCTemplate.SC) == 0) goodrule = false; break; } if (!goodrule) continue; } if ((when&(DRCTemplate.M2|DRCTemplate.M3|DRCTemplate.M4|DRCTemplate.M5|DRCTemplate.M6)) != 0) { switch (getNumMetal()) { case 2: if ((when&DRCTemplate.M2) == 0) goodrule = false; break; case 3: if ((when&DRCTemplate.M3) == 0) goodrule = false; break; case 4: if ((when&DRCTemplate.M4) == 0) goodrule = false; break; case 5: if ((when&DRCTemplate.M5) == 0) goodrule = false; break; case 6: if ((when&DRCTemplate.M6) == 0) goodrule = false; break; } if (!goodrule) continue; } if ((when&DRCTemplate.AC) != 0) { if (!isAlternateActivePolyRules()) continue; } if ((when&DRCTemplate.NAC) != 0) { if (isAlternateActivePolyRules()) continue; } if ((when&DRCTemplate.SV) != 0) { if (isDisallowStackedVias()) continue; } if ((when&DRCTemplate.NSV) != 0) { if (!isDisallowStackedVias()) continue; } // find the layer names Layer lay1 = null; int layert1 = -1; if (theRules[i].name1 != null) { lay1 = findLayer(theRules[i].name1); if (lay1 == null) { System.out.println("Warning: no layer '" + theRules[i].name1 + "' in mocmos technology"); return null; } layert1 = lay1.getIndex(); } Layer lay2 = null; int layert2 = -1; if (theRules[i].name2 != null) { lay2 = findLayer(theRules[i].name2); if (lay2 == null) { System.out.println("Warning: no layer '" + theRules[i].name2 + "' in mocmos technology"); return null; } layert2 = lay2.getIndex(); } // find the index in a two-layer upper-diagonal table int index = -1; if (layert1 >= 0 && layert2 >= 0) { index = getRuleIndex(layert1, layert2); } // find the nodes and arcs associated with the rule PrimitiveNode nty = null; ArcProto aty = null; if (theRules[i].nodeName != null) { if (theRules[i].ruleType == DRCTemplate.ASURROUND) { aty = this.findArcProto(theRules[i].nodeName); if (aty == null) { System.out.println("Warning: no arc '" + theRules[i].nodeName + "' in mocmos technology"); return null; } } else { nty = this.findNodeProto(theRules[i].nodeName); if (nty == null) { System.out.println("Warning: no node '" + theRules[i].nodeName + "' in mocmos technology"); return null; } } } // get more information about the rule double distance = theRules[i].value1; String proc = ""; if ((when&(DRCTemplate.DE|DRCTemplate.SU|DRCTemplate.SC)) != 0) { switch (getRuleSet()) { case DEEPRULES: proc = "DEEP"; break; case SUBMRULES: proc = "SUBM"; break; case SCMOSRULES: proc = "SCMOS"; break; } } String metal = ""; if ((when&(DRCTemplate.M2|DRCTemplate.M3|DRCTemplate.M4|DRCTemplate.M5|DRCTemplate.M6)) != 0) { switch (getNumMetal()) { case 2: metal = "2m"; break; case 3: metal = "3m"; break; case 4: metal = "4m"; break; case 5: metal = "5m"; break; case 6: metal = "6m"; break; } if (!goodrule) continue; } String rule = theRules[i].ruleName; String extraString = metal + proc; if (extraString.length() > 0 && rule.indexOf(extraString) == -1) rule += ", " + extraString; theRules[i].ruleName = new String(rule); // set the rule double [] specValues; switch (theRules[i].ruleType) { case DRCTemplate.MINWID: if (Main.getDebug() && layert1 >= 0 && layert2 >= 0) System.out.println("Error in swap old tech"); rules.minWidth[layert1] = new Double(distance); rules.minWidthRules[layert1] = rule; setLayerMinWidth(theRules[i].name1, theRules[i].ruleName, distance); break; case DRCTemplate.NODSIZ: setDefNodeSize(nty, theRules[i].ruleName, distance, distance, rules); break; case DRCTemplate.SURROUND: setLayerSurroundLayer(theRules[i].ruleName, nty, lay1, lay2, distance, rules.minWidth[lay1.getIndex()].doubleValue()); break; case DRCTemplate.ASURROUND: setArcLayerSurroundLayer(aty, lay1, lay2, distance); break; case DRCTemplate.VIASUR: setLayerSurroundVia(nty, lay1, distance); specValues = nty.getSpecialValues(); specValues[2] = distance; specValues[3] = distance; break; case DRCTemplate.TRAWELL: setTransistorWellSurround(distance); break; case DRCTemplate.TRAPOLY: setTransistorPolyOverhang(distance); break; case DRCTemplate.TRAACTIVE: setTransistorActiveOverhang(distance); break; case DRCTemplate.SPACING: rules.conList[index] = new Double(distance); rules.unConList[index] = new Double(distance); rules.conListRules[index] = rule; rules.unConListRules[index] = rule; break; case DRCTemplate.SPACINGM: rules.conListMulti[index] = new Double(distance); rules.unConListMulti[index] = new Double(distance); rules.conListMultiRules[index] = rule; rules.unConListMultiRules[index] = rule; break; case DRCTemplate.SPACINGW: rules.conListWide[index] = new Double(distance); rules.unConListWide[index] = new Double(distance); rules.conListWideRules[index] = rule; rules.unConListWideRules[index] = rule; break; case DRCTemplate.SPACINGE: rules.edgeList[index] = new Double(distance); rules.edgeListRules[index] = rule; break; case DRCTemplate.CONSPA: rules.conList[index] = new Double(distance); rules.conListRules[index] = rule; break; case DRCTemplate.UCONSPA: rules.unConList[index] = new Double(distance); rules.unConListRules[index] = rule; break; case DRCTemplate.CUTSPA: specValues = nty.getSpecialValues(); specValues[4] = distance; specValues[5] = distance; break; case DRCTemplate.CUTSIZE: specValues = nty.getSpecialValues(); specValues[0] = specValues[1] = distance; int nodeIndex = nty.getPrimNodeIndexInTech(); rules.cutNodeSize[nodeIndex] = new Double(distance); rules.cutNodeSizeRules[nodeIndex] = theRules[i].ruleName; break; case DRCTemplate.CUTSUR: specValues = nty.getSpecialValues(); specValues[2] = distance; specValues[3] = distance; break; default: System.out.println(theRules[i].ruleName + " is an invalid rule type in " + this); } } } rules.calculateNumberOfRules(); return rules; } /** * Method to compare a Rules set with the "factory" set and construct an override string. * @param origDRCRules * @param newDRCRules * @return a StringBuffer that describes any overrides. Returns "" if there are none. */ public static StringBuffer getRuleDifferences(DRCRules origDRCRules, DRCRules newDRCRules) { StringBuffer changes = new StringBuffer(); MOSRules origRules = (MOSRules)origDRCRules; MOSRules newRules = (MOSRules)newDRCRules; // include differences in the wide-rule limit if (!newRules.wideLimit.equals(origRules.wideLimit)) { changes.append("w:"+newRules.wideLimit+";"); } // include differences in layer spacings for(int l1=0; l1<tech.getNumLayers(); l1++) for(int l2=0; l2<=l1; l2++) { int i = tech.getRuleIndex(l2, l1); if (!newRules.conList[i].equals(origRules.conList[i])) { changes.append("c:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conList[i]+";"); } if (!newRules.conListRules[i].equals(origRules.conListRules[i])) { changes.append("cr:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conListRules[i]+";"); } if (!newRules.unConList[i].equals(origRules.unConList[i])) { changes.append("u:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConList[i]+";"); } if (!newRules.unConListRules[i].equals(origRules.unConListRules[i])) { changes.append("ur:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConListRules[i]+";"); } if (!newRules.conListWide[i].equals(origRules.conListWide[i])) { changes.append("cw:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conListWide[i]+";"); } if (!newRules.conListWideRules[i].equals(origRules.conListWideRules[i])) { changes.append("cwr:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conListWideRules[i]+";"); } if (!newRules.unConListWide[i].equals(origRules.unConListWide[i])) { changes.append("uw:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConListWide[i]+";"); } if (!newRules.unConListWideRules[i].equals(origRules.unConListWideRules[i])) { changes.append("uwr:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConListWideRules[i]+";"); } if (!newRules.conListMulti[i].equals(origRules.conListMulti[i])) { changes.append("cm:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conListMulti[i]+";"); } if (!newRules.conListMultiRules[i].equals(origRules.conListMultiRules[i])) { changes.append("cmr:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.conListMultiRules[i]+";"); } if (!newRules.unConListMulti[i].equals(origRules.unConListMulti[i])) { changes.append("um:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConListMulti[i]+";"); } if (!newRules.unConListMultiRules[i].equals(origRules.unConListMultiRules[i])) { changes.append("umr:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.unConListMultiRules[i]+";"); } if (!newRules.edgeList[i].equals(origRules.edgeList[i])) { changes.append("e:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.edgeList[i]+";"); } if (!newRules.edgeListRules[i].equals(origRules.edgeListRules[i])) { changes.append("er:"+tech.getLayer(l1).getName()+"/"+tech.getLayer(l2).getName()+"="+newRules.edgeListRules[i]+";"); } } // include differences in minimum layer widths for(int i=0; i<newRules.numLayers; i++) { if (!newRules.minWidth[i].equals(origRules.minWidth[i])) { changes.append("m:"+tech.getLayer(i).getName()+"="+newRules.minWidth[i]+";"); } if (!newRules.minWidthRules[i].equals(origRules.minWidthRules[i])) { changes.append("mr:"+tech.getLayer(i).getName()+"="+newRules.minWidthRules[i]+";"); } } // include differences in minimum node sizes int j = 0; for(Iterator it = tech.getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); if (!newRules.minNodeSize[j*2].equals(origRules.minNodeSize[j*2]) || !newRules.minNodeSize[j*2+1].equals(origRules.minNodeSize[j*2+1])) { changes.append("n:"+np.getName()+"="+newRules.minNodeSize[j*2]+"/"+newRules.minNodeSize[j*2+1]+";"); } if (!newRules.minNodeSizeRules[j].equals(origRules.minNodeSizeRules[j])) { changes.append("nr:"+np.getName()+"="+newRules.minNodeSizeRules[j]+";"); } j++; } return changes; } /** * Method to be called from DRC:setRules * @param newDRCRules */ public void setRuleVariables(DRCRules newDRCRules) { MOSRules newRules = (MOSRules)newDRCRules; // update variables on the technology // Variable var = newVar(DRCRules.WIDE_LIMIT, newRules.wideLimit); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES, newRules.conList); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES_RULE, newRules.conListRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES, newRules.unConList); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES_RULE, newRules.unConListRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES_WIDE, newRules.conListWide); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES_WIDE_RULE, newRules.conListWideRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES_WIDE, newRules.unConListWide); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES_WIDE_RULE, newRules.unConListWideRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES_MULTI, newRules.conListMulti); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_CONNECTED_DISTANCES_MULTI_RULE, newRules.conListMultiRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES_MULTI, newRules.unConListMulti); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_UNCONNECTED_DISTANCES_MULTI_RULE, newRules.unConListMultiRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_EDGE_DISTANCES, newRules.edgeList); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_EDGE_DISTANCES_RULE, newRules.edgeListRules); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_WIDTH, newRules.minWidth); // if (var != null) var.setDontSave(); // var = newVar(DRCRules.MIN_WIDTH_RULE, newRules.minWidthRules); // if (var != null) var.setDontSave(); // update per-node information int j = 0; for(Iterator it = getNodes(); it.hasNext(); ) { PrimitiveNode np = (PrimitiveNode)it.next(); np.setMinSize(newRules.minNodeSize[j*2].doubleValue(), newRules.minNodeSize[j*2+1].doubleValue(), newRules.minNodeSizeRules[j]); j++; } } /** * Method to implement rule 3.3 which specifies the amount of poly overhang * on a transistor. */ private void setTransistorPolyOverhang(double overhang) { // define the poly box in terms of the central transistor box TechPoint [] pPolyPoints = transistorPolyLayers[P_TYPE].getPoints(); EdgeH pPolyLeft = pPolyPoints[0].getX(); EdgeH pPolyRight = pPolyPoints[1].getX(); pPolyLeft.setAdder(6-overhang); pPolyRight.setAdder(-6+overhang); transistorPolyLayers[P_TYPE].setSerpentineExtentT(overhang); transistorPolyLayers[P_TYPE].setSerpentineExtentB(overhang); TechPoint [] nPolyPoints = transistorPolyLayers[N_TYPE].getPoints(); EdgeH nPolyLeft = nPolyPoints[0].getX(); EdgeH nPolyRight = nPolyPoints[1].getX(); nPolyLeft.setAdder(6-overhang); nPolyRight.setAdder(-6+overhang); transistorPolyLayers[N_TYPE].setSerpentineExtentT(overhang); transistorPolyLayers[N_TYPE].setSerpentineExtentB(overhang); // for the electrical rule versions with split active TechPoint [] pPolyLPoints = transistorPolyLLayers[P_TYPE].getPoints(); TechPoint [] pPolyRPoints = transistorPolyRLayers[P_TYPE].getPoints(); EdgeH pPolyLLeft = pPolyLPoints[0].getX(); EdgeH pPolyRRight = pPolyRPoints[1].getX(); pPolyLLeft.setAdder(6-overhang); pPolyRRight.setAdder(-6+overhang); transistorPolyLLayers[P_TYPE].setSerpentineExtentT(overhang); transistorPolyRLayers[P_TYPE].setSerpentineExtentB(overhang); TechPoint [] nPolyLPoints = transistorPolyLLayers[N_TYPE].getPoints(); TechPoint [] nPolyRPoints = transistorPolyRLayers[N_TYPE].getPoints(); EdgeH nPolyLLeft = nPolyLPoints[0].getX(); EdgeH nPolyRRight = nPolyRPoints[1].getX(); nPolyLLeft.setAdder(6-overhang); nPolyRRight.setAdder(-6+overhang); transistorPolyLLayers[N_TYPE].setSerpentineExtentT(overhang); transistorPolyRLayers[N_TYPE].setSerpentineExtentB(overhang); } /** * Method to implement rule 3.4 which specifies the amount of active overhang * on a transistor. */ private void setTransistorActiveOverhang(double overhang) { TechPoint [] pActivePoints = transistorActiveLayers[P_TYPE].getPoints(); TechPoint [] nActivePoints = transistorActiveLayers[N_TYPE].getPoints(); TechPoint [] pActiveTPoints = transistorActiveTLayers[P_TYPE].getPoints(); TechPoint [] nActiveTPoints = transistorActiveTLayers[N_TYPE].getPoints(); TechPoint [] pActiveBPoints = transistorActiveBLayers[P_TYPE].getPoints(); TechPoint [] nActiveBPoints = transistorActiveBLayers[N_TYPE].getPoints(); TechPoint [] pWellPoints = transistorWellLayers[P_TYPE].getPoints(); TechPoint [] nWellPoints = transistorWellLayers[N_TYPE].getPoints(); TechPoint [] pSelectPoints = transistorSelectLayers[P_TYPE].getPoints(); TechPoint [] nSelectPoints = transistorSelectLayers[N_TYPE].getPoints(); // pickup extension of well about active (2.3) EdgeH pActiveLeft = pActivePoints[0].getX(); EdgeH pWellLeft = pWellPoints[0].getX(); double wellOverhang = pActiveLeft.getAdder() - pWellLeft.getAdder(); // define the active box in terms of the central transistor box EdgeV pActiveBottom = pActivePoints[0].getY(); EdgeV pActiveTop = pActivePoints[1].getY(); pActiveBottom.setAdder(10-overhang); pActiveTop.setAdder(-10+overhang); EdgeV nActiveBottom = nActivePoints[0].getY(); EdgeV nActiveTop = nActivePoints[1].getY(); nActiveBottom.setAdder(10-overhang); nActiveTop.setAdder(-10+overhang); // for the electrical rule versions with split active EdgeV pActiveBBottom = pActiveBPoints[0].getY(); EdgeV pActiveTTop = pActiveTPoints[1].getY(); pActiveBBottom.setAdder(10-overhang); pActiveTTop.setAdder(-10+overhang); EdgeV nActiveBBottom = nActiveBPoints[0].getY(); EdgeV nActiveTTop = nActiveTPoints[1].getY(); nActiveBBottom.setAdder(10-overhang); nActiveTTop.setAdder(-10+overhang); // extension of select about active = 2 (4.2) EdgeV pSelectBottom = pSelectPoints[0].getY(); EdgeV pSelectTop = pSelectPoints[1].getY(); pSelectBottom.setAdder(pActiveBottom.getAdder()-2); pSelectTop.setAdder(pActiveTop.getAdder()+2); EdgeV nSelectBottom = nSelectPoints[0].getY(); EdgeV nSelectTop = nSelectPoints[1].getY(); nSelectBottom.setAdder(nActiveBottom.getAdder()-2); nSelectTop.setAdder(nActiveTop.getAdder()+2); // extension of well about active (2.3) EdgeV pWellBottom = pWellPoints[0].getY(); EdgeV pWellTop = pWellPoints[1].getY(); pWellBottom.setAdder(pActiveBottom.getAdder()-wellOverhang); pWellTop.setAdder(pActiveTop.getAdder()+wellOverhang); EdgeV nWellBottom = nWellPoints[0].getY(); EdgeV nWellTop = nWellPoints[1].getY(); nWellBottom.setAdder(nActiveBottom.getAdder()-wellOverhang); nWellTop.setAdder(nActiveTop.getAdder()+wellOverhang); // the serpentine active overhang SizeOffset so = transistorNodes[P_TYPE].getProtoSizeOffset(); double halfPolyWidth = (transistorNodes[P_TYPE].getDefHeight() - so.getHighYOffset() - so.getLowYOffset()) / 2; transistorActiveLayers[P_TYPE].setSerpentineLWidth(halfPolyWidth+overhang); transistorActiveLayers[P_TYPE].setSerpentineRWidth(halfPolyWidth+overhang); transistorActiveTLayers[P_TYPE].setSerpentineRWidth(halfPolyWidth+overhang); transistorActiveBLayers[P_TYPE].setSerpentineLWidth(halfPolyWidth+overhang); transistorActiveLayers[N_TYPE].setSerpentineLWidth(halfPolyWidth+overhang); transistorActiveLayers[N_TYPE].setSerpentineRWidth(halfPolyWidth+overhang); transistorActiveTLayers[N_TYPE].setSerpentineRWidth(halfPolyWidth+overhang); transistorActiveBLayers[N_TYPE].setSerpentineLWidth(halfPolyWidth+overhang); transistorSelectLayers[P_TYPE].setSerpentineLWidth(halfPolyWidth+overhang+2); transistorSelectLayers[P_TYPE].setSerpentineRWidth(halfPolyWidth+overhang+2); transistorSelectLayers[N_TYPE].setSerpentineLWidth(halfPolyWidth+overhang+2); transistorSelectLayers[N_TYPE].setSerpentineRWidth(halfPolyWidth+overhang+2); transistorWellLayers[P_TYPE].setSerpentineLWidth(halfPolyWidth+overhang+wellOverhang); transistorWellLayers[P_TYPE].setSerpentineRWidth(halfPolyWidth+overhang+wellOverhang); transistorWellLayers[N_TYPE].setSerpentineLWidth(halfPolyWidth+overhang+wellOverhang); transistorWellLayers[N_TYPE].setSerpentineRWidth(halfPolyWidth+overhang+wellOverhang); } /** * Method to implement rule 2.3 which specifies the amount of well surround * about active on a transistor. */ private void setTransistorWellSurround(double overhang) { // define the well box in terms of the active box TechPoint [] pActivePoints = transistorActiveLayers[P_TYPE].getPoints(); TechPoint [] nActivePoints = transistorActiveLayers[N_TYPE].getPoints(); TechPoint [] pWellPoints = transistorWellLayers[P_TYPE].getPoints(); TechPoint [] nWellPoints = transistorWellLayers[N_TYPE].getPoints(); EdgeH pWellLeft = pWellPoints[0].getX(); EdgeH pWellRight = pWellPoints[1].getX(); EdgeV pWellBottom = pWellPoints[0].getY(); EdgeV pWellTop = pWellPoints[1].getY(); EdgeH pActiveLeft = pActivePoints[0].getX(); EdgeH pActiveRight = pActivePoints[1].getX(); EdgeV pActiveBottom = pActivePoints[0].getY(); EdgeV pActiveTop = pActivePoints[1].getY(); EdgeH nWellLeft = nWellPoints[0].getX(); EdgeH nWellRight = nWellPoints[1].getX(); EdgeV nWellBottom = nWellPoints[0].getY(); EdgeV nWellTop = nWellPoints[1].getY(); EdgeH nActiveLeft = nActivePoints[0].getX(); EdgeH nActiveRight = nActivePoints[1].getX(); EdgeV nActiveBottom = nActivePoints[0].getY(); EdgeV nActiveTop = nActivePoints[1].getY(); pWellLeft.setAdder(pActiveLeft.getAdder()-overhang); pWellRight.setAdder(pActiveRight.getAdder()+overhang); pWellBottom.setAdder(pActiveBottom.getAdder()-overhang); pWellTop.setAdder(pActiveTop.getAdder()+overhang); nWellLeft.setAdder(nActiveLeft.getAdder()-overhang); nWellRight.setAdder(nActiveRight.getAdder()+overhang); nWellBottom.setAdder(nActiveBottom.getAdder()-overhang); nWellTop.setAdder(nActiveTop.getAdder()+overhang); // the serpentine poly overhang transistorWellLayers[P_TYPE].setSerpentineLWidth(overhang+4); transistorWellLayers[P_TYPE].setSerpentineRWidth(overhang+4); transistorWellLayers[N_TYPE].setSerpentineLWidth(overhang+4); transistorWellLayers[N_TYPE].setSerpentineRWidth(overhang+4); transistorWellLayers[P_TYPE].setSerpentineExtentT(overhang); transistorWellLayers[P_TYPE].setSerpentineExtentB(overhang); transistorWellLayers[N_TYPE].setSerpentineExtentT(overhang); transistorWellLayers[N_TYPE].setSerpentineExtentB(overhang); } /******************** OVERRIDES ********************/ /** * This method overrides the one in Technology because it knows about equivalence layers for MOCMOS. */ public boolean sameLayer(Layer layer1, Layer layer2) { if (layer1 == layer2) return true; if (layer1 == poly1_lay && layer2 == transistorPoly_lay) return true; if (layer2 == poly1_lay && layer1 == transistorPoly_lay) return true; return false; } /** * Method to convert old primitive names to their proper NodeProtos. * @param name the name of the old primitive. * @return the proper PrimitiveNode to use (or null if none can be determined). */ public PrimitiveNode convertOldNodeName(String name) { if (name.equals("Metal-1-Substrate-Con")) return(metalWellContactNodes[N_TYPE]); if (name.equals("Metal-1-Well-Con")) return(metalWellContactNodes[P_TYPE]); return null; } public int getNumMetals() { return MoCMOS.getNumMetal(); } /******************** OPTIONS ********************/ private static Pref cacheNumberOfMetalLayers = TechPref.makeIntPref(tech, "MoCMOSNumberOfMetalLayers", getTechnologyPreferences(), 4); static { cacheNumberOfMetalLayers.attachToObject(tech, "Technology/Technology tab", "MOSIS CMOS: Number of Metal Layers"); } /** * Method to tell the number of metal layers in the MoCMOS technology. * The default is "4". * @return the number of metal layers in the MoCMOS technology (from 2 to 6). */ public static int getNumMetal() { return cacheNumberOfMetalLayers.getInt(); } /** * Method to set the number of metal layers in the MoCMOS technology. * @param num the number of metal layers in the MoCMOS technology (from 2 to 6). */ public static void setNumMetal(int num) { cacheNumberOfMetalLayers.setInt(num); } private static Pref cacheRuleSet = TechPref.makeIntPref("MoCMOSRuleSet", getTechnologyPreferences(), 1); static { Pref.Meaning m = cacheRuleSet.attachToObject(tech, "Technology/Technology tab", "MOSIS CMOS rule set"); m.setTrueMeaning(new String[] {"SCMOS", "Submicron", "Deep"}); } /** * Method to tell the current rule set for this Technology. * @return the current rule set for this Technology:<BR> * 0: SCMOS rules<BR> * 1: Submicron rules (the default)<BR> * 2: Deep rules */ public static int getRuleSet() { return cacheRuleSet.getInt(); } /** * Method to set the rule set for this Technology. * @param set the new rule set for this Technology:<BR> * 0: SCMOS rules<BR> * 1: Submicron rules<BR> * 2: Deep rules */ public static void setRuleSet(int set) { cacheRuleSet.setInt(set); } private static Pref cacheSecondPolysilicon = TechPref.makeBooleanPref("MoCMOSSecondPolysilicon", getTechnologyPreferences(), false); static { cacheSecondPolysilicon.attachToObject(tech, "Technology/Technology tab", "MOSIS CMOS: Second Polysilicon Layer"); } /** * Method to tell the number of polysilicon layers in this Technology. * The default is false. * @return true if there are 2 polysilicon layers in this Technology. * If false, there is only 1 polysilicon layer. */ public static boolean isSecondPolysilicon() { return cacheSecondPolysilicon.getBoolean(); } /** * Method to set a second polysilicon layer in this Technology. * @param on true if there are 2 polysilicon layers in this Technology. */ public static void setSecondPolysilicon(boolean on) { cacheSecondPolysilicon.setBoolean(on); } private static Pref cacheDisallowStackedVias = TechPref.makeBooleanPref("MoCMOSDisallowStackedVias", getTechnologyPreferences(), false); static { cacheDisallowStackedVias.attachToObject(tech, "Technology/Technology tab", "MOSIS CMOS: Disallow Stacked Vias"); } /** * Method to determine whether this Technology disallows stacked vias. * The default is false (they are allowed). * @return true if the MOCMOS technology disallows stacked vias. */ public static boolean isDisallowStackedVias() { return cacheDisallowStackedVias.getBoolean(); } /** * Method to set whether this Technology disallows stacked vias. * @param on true if the MOCMOS technology will allow disallows vias. */ public static void setDisallowStackedVias(boolean on) { cacheDisallowStackedVias.setBoolean(on); } private static Pref cacheAlternateActivePolyRules = TechPref.makeBooleanPref("MoCMOSAlternateActivePolyRules", getTechnologyPreferences(), false); static { cacheAlternateActivePolyRules.attachToObject(tech, "Technology/Technology tab", "MOSIS CMOS: Alternate Active and Poly Contact Rules"); } /** * Method to determine whether this Technology is using alternate Active and Poly contact rules. * The default is false. * @return true if the MOCMOS technology is using alternate Active and Poly contact rules. */ public static boolean isAlternateActivePolyRules() { return cacheAlternateActivePolyRules.getBoolean(); } /** * Method to set whether this Technology is using alternate Active and Poly contact rules. * @param on true if the MOCMOS technology is to use alternate Active and Poly contact rules. */ public static void setAlternateActivePolyRules(boolean on) { cacheAlternateActivePolyRules.setBoolean(on); } /** set if no stacked vias allowed */ private static final int MOCMOSNOSTACKEDVIAS = 01; // /** set for stick-figure display */ private static final int MOCMOSSTICKFIGURE = 02; /** number of metal layers */ private static final int MOCMOSMETALS = 034; /** 2-metal rules */ private static final int MOCMOS2METAL = 0; /** 3-metal rules */ private static final int MOCMOS3METAL = 04; /** 4-metal rules */ private static final int MOCMOS4METAL = 010; /** 5-metal rules */ private static final int MOCMOS5METAL = 014; /** 6-metal rules */ private static final int MOCMOS6METAL = 020; /** type of rules */ private static final int MOCMOSRULESET = 0140; /** set if submicron rules in use */ private static final int MOCMOSSUBMRULES = 0; /** set if deep rules in use */ private static final int MOCMOSDEEPRULES = 040; /** set if standard SCMOS rules in use */ private static final int MOCMOSSCMOSRULES = 0100; /** set to use alternate active/poly rules */ private static final int MOCMOSALTAPRULES = 0200; /** set to use second polysilicon layer */ private static final int MOCMOSTWOPOLY = 0400; // /** set to show special transistors */ private static final int MOCMOSSPECIALTRAN = 01000; /** * Method to convert any old-style state information to the new options. */ /** * Method to convert any old-style variable information to the new options. * May be overrideen in subclasses. * @param varName name of variable * @param value value of variable * @return true if variable was converted */ public boolean convertOldVariable(String varName, Object value) { if (!varName.equalsIgnoreCase(TECH_LAST_STATE.getName())) return false; if (!(value instanceof Integer)) return false; int oldBits = ((Integer)value).intValue(); boolean oldNoStackedVias = (oldBits&MOCMOSNOSTACKEDVIAS) != 0; Pref.changedMeaningVariable(cacheDisallowStackedVias.getMeaning(), new Integer(oldNoStackedVias?1:0)); int numMetals = 0; switch (oldBits&MOCMOSMETALS) { case MOCMOS2METAL: numMetals = 2; break; case MOCMOS3METAL: numMetals = 3; break; case MOCMOS4METAL: numMetals = 4; break; case MOCMOS5METAL: numMetals = 5; break; case MOCMOS6METAL: numMetals = 6; break; } Pref.changedMeaningVariable(cacheNumberOfMetalLayers.getMeaning(), new Integer(numMetals)); int ruleSet = 0; switch (oldBits&MOCMOSRULESET) { case MOCMOSSUBMRULES: ruleSet = SUBMRULES; break; case MOCMOSDEEPRULES: ruleSet = DEEPRULES; break; case MOCMOSSCMOSRULES: ruleSet = SCMOSRULES; break; } Pref.changedMeaningVariable(cacheRuleSet.getMeaning(), new Integer(ruleSet)); boolean alternateContactRules = (oldBits&MOCMOSALTAPRULES) != 0; Pref.changedMeaningVariable(cacheAlternateActivePolyRules.getMeaning(), new Integer(alternateContactRules?1:0)); boolean secondPoly = (oldBits&MOCMOSTWOPOLY) != 0; Pref.changedMeaningVariable(cacheSecondPolysilicon.getMeaning(), new Integer(secondPoly?1:0)); return true; } /******************** NODE DESCRIPTION (GRAPHICAL) ********************/ /** * Method to set the surround distance of layer "outerlayer" from layer "innerlayer" * in node "nty" to "surround". The array "minsize" is the minimum size of each layer. */ private void setLayerSurroundLayer(String ruleName, PrimitiveNode nty, Layer outerLayer, Layer innerLayer, double surround, double minSizeValue) { // find the inner layer Technology.NodeLayer inLayer = nty.findNodeLayer(innerLayer, false); if (inLayer == null) { System.out.println("Internal error in " + getTechDesc() + " surround computation. Layer '" + innerLayer.getName() + "' is not valid in '" + nty.getName() + "'"); return; } // find the outer layer Technology.NodeLayer outLayer = nty.findNodeLayer(outerLayer, false); if (outLayer == null) { System.out.println("Internal error in " + getTechDesc() + " surround computation. Layer '" + outerLayer.getName() + "' is not valid in '" + nty.getName() + "'"); return; } // determine if minimum size design rules are met TechPoint [] inPoints = inLayer.getPoints(); EdgeH inLeft = inPoints[0].getX(); EdgeH inRight = inPoints[1].getX(); EdgeV inBottom = inPoints[0].getY(); EdgeV inTop = inPoints[1].getY(); double leftIndent = inLeft.getAdder() - surround; double rightIndent = inRight.getAdder() + surround; double bottomIndent = inBottom.getAdder() - surround; double topIndent = inTop.getAdder() + surround; double xSize = nty.getDefWidth() - leftIndent - rightIndent; double ySize = nty.getDefHeight() - bottomIndent - topIndent; //int outerLayerIndex = outerLayer.getIndex(); //double minSizeValue = minSize[outerLayerIndex].doubleValue(); //double minSizeValue = minSize[outerLayerIndex].doubleValue(); if (xSize < minSizeValue || ySize < minSizeValue) { // make it irregular to force the proper minimum size if (xSize < minSizeValue) rightIndent -= minSizeValue - xSize; if (ySize < minSizeValue) topIndent -= minSizeValue - ySize; } TechPoint [] outPoints = outLayer.getPoints(); EdgeH outLeft = outPoints[0].getX(); EdgeH outRight = outPoints[1].getX(); EdgeV outBottom = outPoints[0].getY(); EdgeV outTop = outPoints[1].getY(); boolean hasChanged = false; // describe the error String errorMessage = "Layer surround error of outer layer '" + outerLayer.getName() + "' and inner layer '" + innerLayer.getName() + "'in '" + nty.getName() + "'('" +getTechDesc() + "'):"; leftIndent = DBMath.round(leftIndent); rightIndent = DBMath.round(rightIndent); topIndent = DBMath.round(topIndent); bottomIndent = DBMath.round(bottomIndent); if (!DBMath.areEquals(outLeft.getAdder(), leftIndent)) { outLeft.setAdder(leftIndent); hasChanged = true; errorMessage += " left=" + leftIndent; } if (!DBMath.areEquals(outRight.getAdder(), rightIndent)) { outRight.setAdder(rightIndent); hasChanged = true; errorMessage += " right=" + rightIndent; } if (!DBMath.areEquals(outTop.getAdder(), topIndent)) { outTop.setAdder(topIndent); hasChanged = true; errorMessage += " top=" + topIndent; } if (!DBMath.areEquals(outBottom.getAdder(), bottomIndent)) { outBottom.setAdder(bottomIndent); hasChanged = true; errorMessage += " bottom=" + bottomIndent; } errorMessage += "(rule " + ruleName + ")"; // Message printed only if developer turns local flag on if (hasChanged && Main.LOCALDEBUGFLAG) System.out.println(errorMessage); } }
false
true
private MoCMOS() { super("mocmos"); setTechShortName("MOSIS CMOS"); setTechDesc("MOSIS CMOS"); setFactoryScale(200, true); // in nanometers: really 0.2 micron setNoNegatedArcs(); setStaticTechnology(); setFactoryTransparentLayers(new Color [] { new Color( 96,209,255), // Metal-1 new Color(255,155,192), // Polysilicon-1 new Color(107,226, 96), // Active new Color(224, 95,255), // Metal-2 new Color(247,251, 20) // Metal-3 }); setFactoryResolution(0.01); // value in lambdas 0.005um -> 0.05 lambdas foundries.add(new Foundry(Foundry.MOSIS_FOUNDRY, DRCTemplate.MOSIS)); foundries.add(new Foundry("TSMC", DRCTemplate.TSMC)); setFactorySelecedFound(Foundry.MOSIS_FOUNDRY); // default //**************************************** LAYERS **************************************** Layer[] metalLayers = new Layer[6]; // 1 -> 6 /** metal-1 layer */ metalLayers[0] = Layer.newInstance(this, "Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-2 layer */ metalLayers[1] = Layer.newInstance(this, "Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** metal-3 layer */ metalLayers[2] = Layer.newInstance(this, "Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-4 layer */ metalLayers[3] = Layer.newInstance(this, "Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** metal-5 layer */ metalLayers[4] = Layer.newInstance(this, "Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** metal-6 layer */ metalLayers[5] = Layer.newInstance(this, "Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** poly layer */ poly1_lay = Layer.newInstance(this, "Polysilicon-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly2 layer */ Layer poly2_lay = Layer.newInstance(this, "Polysilicon-2", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X Layer[] activeLayers = new Layer[2]; /** P active layer */ activeLayers[P_TYPE] = Layer.newInstance(this, "P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** N active layer */ activeLayers[N_TYPE] = Layer.newInstance(this, "N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX Layer[] selectLayers = new Layer[2]; /** P Select layer */ selectLayers[P_TYPE] = Layer.newInstance(this, "P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** N Select layer */ selectLayers[N_TYPE] = Layer.newInstance(this, "N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// Layer[] wellLayers = new Layer[2]; /** P Well layer */ wellLayers[P_TYPE] = Layer.newInstance(this, "P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** N Well implant */ wellLayers[N_TYPE] = Layer.newInstance(this, "N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** poly cut layer */ Layer polyCutLayer = Layer.newInstance(this, "Poly-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** active cut layer */ Layer activeCut_lay = Layer.newInstance(this, "Active-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via1 layer */ Layer via1_lay = Layer.newInstance(this, "Via1", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via2 layer */ Layer via2_lay = Layer.newInstance(this, "Via2", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via3 layer */ Layer via3_lay = Layer.newInstance(this, "Via3", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via4 layer */ Layer via4_lay = Layer.newInstance(this, "Via4", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via5 layer */ Layer via5_lay = Layer.newInstance(this, "Via5", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** passivation layer */ Layer passivation_lay = Layer.newInstance(this, "Passivation", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 100,100,100, 1.0,true, new int[] { 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000, // 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000}));// /** poly/trans layer */ transistorPoly_lay = Layer.newInstance(this, "Transistor-Poly", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly cap layer */ Layer polyCap_lay = Layer.newInstance(this, "Poly-Cap", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 0,0,0, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** P act well layer */ Layer pActiveWell_lay = Layer.newInstance(this, "P-Active-Well", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,false, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** Silicide block */ /** Resist Protection Oxide (RPO) Same graphics as in 90nm tech */ Layer silicideBlock_lay = Layer.newInstance(this, "Silicide-Block", // new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 230,230,230, 1.0,false, // new int[] { 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000}));// new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 192,255,255, 0.5,true, new int[] { 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000, /* */ 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000}));/* */ /** Thick active */ Layer thickActive_lay = Layer.newInstance(this, "Thick-Active", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,0,0, 1.0,false, new int[] { 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020}));// X X /** pseudo metal 1 */ Layer pseudoMetal1_lay = Layer.newInstance(this, "Pseudo-Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** pseudo metal-2 */ Layer pseudoMetal2_lay = Layer.newInstance(this, "Pseudo-Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-3 */ Layer pseudoMetal3_lay = Layer.newInstance(this, "Pseudo-Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-4 */ Layer pseudoMetal4_lay = Layer.newInstance(this, "Pseudo-Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** pseudo metal-5 */ Layer pseudoMetal5_lay = Layer.newInstance(this, "Pseudo-Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** pseudo metal-6 */ Layer pseudoMetal6_lay = Layer.newInstance(this, "Pseudo-Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** pseudo poly layer */ Layer pseudoPoly1_lay = Layer.newInstance(this, "Pseudo-Polysilicon", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 1.0,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** pseudo poly2 layer */ Layer pseudoPoly2_lay = Layer.newInstance(this, "Pseudo-Electrode", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X /** pseudo P active */ Layer pseudoPActive_lay = Layer.newInstance(this, "Pseudo-P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo N active */ Layer pseudoNActive_lay = Layer.newInstance(this, "Pseudo-N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo P Select */ Layer pseudoPSelect_lay = Layer.newInstance(this, "Pseudo-P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo N Select */ Layer pseudoNSelect_lay = Layer.newInstance(this, "Pseudo-N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// /** pseudo P Well */ Layer pseudoPWell_lay = Layer.newInstance(this, "Pseudo-P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** pseudo N Well */ Layer pseudoNWell_lay = Layer.newInstance(this, "Pseudo-N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** pad frame */ Layer padFrame_lay = Layer.newInstance(this, "Pad-Frame", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, 0, 255,0,0, 1.0,false, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); // The layer functions metalLayers[0].setFunction(Layer.Function.METAL1); // Metal-1 metalLayers[1].setFunction(Layer.Function.METAL2); // Metal-2 metalLayers[2].setFunction(Layer.Function.METAL3); // Metal-3 metalLayers[3].setFunction(Layer.Function.METAL4); // Metal-4 metalLayers[4].setFunction(Layer.Function.METAL5); // Metal-5 metalLayers[5].setFunction(Layer.Function.METAL6); // Metal-6 poly1_lay.setFunction(Layer.Function.POLY1); // Polysilicon-1 poly2_lay.setFunction(Layer.Function.POLY2); // Polysilicon-2 activeLayers[P_TYPE].setFunction(Layer.Function.DIFFP); // P-Active activeLayers[N_TYPE].setFunction(Layer.Function.DIFFN); // N-Active selectLayers[P_TYPE].setFunction(Layer.Function.IMPLANTP); // P-Select selectLayers[N_TYPE].setFunction(Layer.Function.IMPLANTN); // N-Select wellLayers[P_TYPE].setFunction(Layer.Function.WELLP); // P-Well wellLayers[N_TYPE].setFunction(Layer.Function.WELLN); // N-Well polyCutLayer.setFunction(Layer.Function.CONTACT1, Layer.Function.CONPOLY); // Poly-Cut activeCut_lay.setFunction(Layer.Function.CONTACT1, Layer.Function.CONDIFF); // Active-Cut via1_lay.setFunction(Layer.Function.CONTACT2, Layer.Function.CONMETAL); // Via-1 via2_lay.setFunction(Layer.Function.CONTACT3, Layer.Function.CONMETAL); // Via-2 via3_lay.setFunction(Layer.Function.CONTACT4, Layer.Function.CONMETAL); // Via-3 via4_lay.setFunction(Layer.Function.CONTACT5, Layer.Function.CONMETAL); // Via-4 via5_lay.setFunction(Layer.Function.CONTACT6, Layer.Function.CONMETAL); // Via-5 passivation_lay.setFunction(Layer.Function.OVERGLASS); // Passivation transistorPoly_lay.setFunction(Layer.Function.GATE); // Transistor-Poly polyCap_lay.setFunction(Layer.Function.CAP); // Poly-Cap pActiveWell_lay.setFunction(Layer.Function.DIFFP); // P-Active-Well silicideBlock_lay.setFunction(Layer.Function.ART); // Silicide-Block thickActive_lay.setFunction(Layer.Function.DIFF, Layer.Function.THICK); // Thick-Active pseudoMetal1_lay.setFunction(Layer.Function.METAL1, Layer.Function.PSEUDO); // Pseudo-Metal-1 pseudoMetal2_lay.setFunction(Layer.Function.METAL2, Layer.Function.PSEUDO); // Pseudo-Metal-2 pseudoMetal3_lay.setFunction(Layer.Function.METAL3, Layer.Function.PSEUDO); // Pseudo-Metal-3 pseudoMetal4_lay.setFunction(Layer.Function.METAL4, Layer.Function.PSEUDO); // Pseudo-Metal-4 pseudoMetal5_lay.setFunction(Layer.Function.METAL5, Layer.Function.PSEUDO); // Pseudo-Metal-5 pseudoMetal6_lay.setFunction(Layer.Function.METAL6, Layer.Function.PSEUDO); // Pseudo-Metal-6 pseudoPoly1_lay.setFunction(Layer.Function.POLY1, Layer.Function.PSEUDO); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFunction(Layer.Function.POLY2, Layer.Function.PSEUDO); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFunction(Layer.Function.DIFFP, Layer.Function.PSEUDO); // Pseudo-P-Active pseudoNActive_lay.setFunction(Layer.Function.DIFFN, Layer.Function.PSEUDO); // Pseudo-N-Active pseudoPSelect_lay.setFunction(Layer.Function.IMPLANTP, Layer.Function.PSEUDO); // Pseudo-P-Select pseudoNSelect_lay.setFunction(Layer.Function.IMPLANTN, Layer.Function.PSEUDO); // Pseudo-N-Select pseudoPWell_lay.setFunction(Layer.Function.WELLP, Layer.Function.PSEUDO); // Pseudo-P-Well pseudoNWell_lay.setFunction(Layer.Function.WELLN, Layer.Function.PSEUDO); // Pseudo-N-Well padFrame_lay.setFunction(Layer.Function.ART); // Pad-Frame // The CIF names metalLayers[0].setFactoryCIFLayer("CMF"); // Metal-1 metalLayers[1].setFactoryCIFLayer("CMS"); // Metal-2 metalLayers[2].setFactoryCIFLayer("CMT"); // Metal-3 metalLayers[3].setFactoryCIFLayer("CMQ"); // Metal-4 metalLayers[4].setFactoryCIFLayer("CMP"); // Metal-5 metalLayers[5].setFactoryCIFLayer("CM6"); // Metal-6 poly1_lay.setFactoryCIFLayer("CPG"); // Polysilicon-1 poly2_lay.setFactoryCIFLayer("CEL"); // Polysilicon-2 activeLayers[P_TYPE].setFactoryCIFLayer("CAA"); // P-Active activeLayers[N_TYPE].setFactoryCIFLayer("CAA"); // N-Active selectLayers[P_TYPE].setFactoryCIFLayer("CSP"); // P-Select selectLayers[N_TYPE].setFactoryCIFLayer("CSN"); // N-Select wellLayers[P_TYPE].setFactoryCIFLayer("CWP"); // P-Well wellLayers[N_TYPE].setFactoryCIFLayer("CWN"); // N-Well polyCutLayer.setFactoryCIFLayer("CCC"); // Poly-Cut activeCut_lay.setFactoryCIFLayer("CCC"); // Active-Cut via1_lay.setFactoryCIFLayer("CVA"); // Via-1 via2_lay.setFactoryCIFLayer("CVS"); // Via-2 via3_lay.setFactoryCIFLayer("CVT"); // Via-3 via4_lay.setFactoryCIFLayer("CVQ"); // Via-4 via5_lay.setFactoryCIFLayer("CV5"); // Via-5 passivation_lay.setFactoryCIFLayer("COG"); // Passivation transistorPoly_lay.setFactoryCIFLayer("CPG"); // Transistor-Poly polyCap_lay.setFactoryCIFLayer("CPC"); // Poly-Cap pActiveWell_lay.setFactoryCIFLayer("CAA"); // P-Active-Well silicideBlock_lay.setFactoryCIFLayer("CSB"); // Silicide-Block thickActive_lay.setFactoryCIFLayer("CTA"); // Thick-Active pseudoMetal1_lay.setFactoryCIFLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryCIFLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryCIFLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryCIFLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryCIFLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryCIFLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryCIFLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactoryCIFLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactoryCIFLayer("CSP"); // Pseudo-P-Select pseudoNSelect_lay.setFactoryCIFLayer("CSN"); // Pseudo-N-Select pseudoPWell_lay.setFactoryCIFLayer("CWP"); // Pseudo-P-Well pseudoNWell_lay.setFactoryCIFLayer("CWN"); // Pseudo-N-Well padFrame_lay.setFactoryCIFLayer("XP"); // Pad-Frame // The GDS names metalLayers[0].setFactoryGDSLayer("49, 80p, 80t", Foundry.MOSIS_FOUNDRY); // Metal-1 Mosis metalLayers[0].setFactoryGDSLayer("16", Foundry.TSMC_FOUNDRY); // Metal-1 TSMC metalLayers[1].setFactoryGDSLayer("51, 82p, 82t", Foundry.MOSIS_FOUNDRY); // Metal-2 metalLayers[1].setFactoryGDSLayer("18", Foundry.TSMC_FOUNDRY); // Metal-2 metalLayers[2].setFactoryGDSLayer("62, 93p, 93t", Foundry.MOSIS_FOUNDRY); // Metal-3 metalLayers[2].setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Metal-3 metalLayers[3].setFactoryGDSLayer("31, 63p, 63t", Foundry.MOSIS_FOUNDRY); // Metal-4 metalLayers[3].setFactoryGDSLayer("31", Foundry.TSMC_FOUNDRY); metalLayers[4].setFactoryGDSLayer("33, 64p, 64t", Foundry.MOSIS_FOUNDRY); // Metal-5 metalLayers[4].setFactoryGDSLayer("33", Foundry.TSMC_FOUNDRY); // Metal-5 metalLayers[5].setFactoryGDSLayer("37, 68p, 68t", Foundry.MOSIS_FOUNDRY); // Metal-6 metalLayers[5].setFactoryGDSLayer("38", Foundry.TSMC_FOUNDRY); // Metal-6 poly1_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Polysilicon-1 poly1_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Polysilicon-1 transistorPoly_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Transistor-Poly transistorPoly_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Transistor-Poly poly2_lay.setFactoryGDSLayer("56", Foundry.MOSIS_FOUNDRY); // Polysilicon-2 activeLayers[P_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active activeLayers[P_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active activeLayers[N_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // N-Active activeLayers[N_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // N-Active pActiveWell_lay.setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active-Well pActiveWell_lay.setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active-Well selectLayers[P_TYPE].setFactoryGDSLayer("44", Foundry.MOSIS_FOUNDRY); // P-Select selectLayers[P_TYPE].setFactoryGDSLayer("7", Foundry.TSMC_FOUNDRY); // P-Select selectLayers[N_TYPE].setFactoryGDSLayer("45", Foundry.MOSIS_FOUNDRY); // N-Select selectLayers[N_TYPE].setFactoryGDSLayer("8", Foundry.TSMC_FOUNDRY); // N-Select wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.MOSIS_FOUNDRY); // P-Well wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.TSMC_FOUNDRY); // P-Well wellLayers[N_TYPE].setFactoryGDSLayer("42", Foundry.MOSIS_FOUNDRY); // N-Well wellLayers[N_TYPE].setFactoryGDSLayer("2", Foundry.TSMC_FOUNDRY); // N-Well polyCutLayer.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Poly-Cut polyCutLayer.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Poly-Cut activeCut_lay.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Active-Cut activeCut_lay.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Active-Cut via1_lay.setFactoryGDSLayer("50", Foundry.MOSIS_FOUNDRY); // Via-1 via1_lay.setFactoryGDSLayer("17", Foundry.TSMC_FOUNDRY); // Via-1 via2_lay.setFactoryGDSLayer("61", Foundry.MOSIS_FOUNDRY); // Via-2 via2_lay.setFactoryGDSLayer("27", Foundry.TSMC_FOUNDRY); // Via-2 via3_lay.setFactoryGDSLayer("30", Foundry.MOSIS_FOUNDRY); // Via-3 via3_lay.setFactoryGDSLayer("29", Foundry.TSMC_FOUNDRY); // Via-3 via4_lay.setFactoryGDSLayer("32", Foundry.MOSIS_FOUNDRY); // Via-4 via4_lay.setFactoryGDSLayer("32", Foundry.TSMC_FOUNDRY); // Via-4 via5_lay.setFactoryGDSLayer("36", Foundry.MOSIS_FOUNDRY); // Via-5 via5_lay.setFactoryGDSLayer("39", Foundry.TSMC_FOUNDRY); // Via-5 passivation_lay.setFactoryGDSLayer("52", Foundry.MOSIS_FOUNDRY); // Passivation passivation_lay.setFactoryGDSLayer("19", Foundry.TSMC_FOUNDRY); // Passivation polyCap_lay.setFactoryGDSLayer("28", Foundry.MOSIS_FOUNDRY); // Poly-Cap polyCap_lay.setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Poly-Cap silicideBlock_lay.setFactoryGDSLayer("29", Foundry.MOSIS_FOUNDRY); // Silicide-Block silicideBlock_lay.setFactoryGDSLayer("34", Foundry.TSMC_FOUNDRY); // Silicide-Block thickActive_lay.setFactoryGDSLayer("60", Foundry.MOSIS_FOUNDRY); // Thick-Active thickActive_lay.setFactoryGDSLayer("4", Foundry.TSMC_FOUNDRY); // Thick-Active pseudoMetal1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Active pseudoNActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Active pseudoPSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Select pseudoNSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Select pseudoPWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Well pseudoNWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Well padFrame_lay.setFactoryGDSLayer("26", Foundry.MOSIS_FOUNDRY); // Pad-Frame padFrame_lay.setFactoryGDSLayer("26", Foundry.TSMC_FOUNDRY); // Pad-Frame // The Skill names metalLayers[0].setFactorySkillLayer("metal1"); // Metal-1 metalLayers[1].setFactorySkillLayer("metal2"); // Metal-2 metalLayers[2].setFactorySkillLayer("metal3"); // Metal-3 metalLayers[3].setFactorySkillLayer("metal4"); // Metal-4 metalLayers[4].setFactorySkillLayer("metal5"); // Metal-5 metalLayers[5].setFactorySkillLayer("metal6"); // Metal-6 poly1_lay.setFactorySkillLayer("poly"); // Polysilicon-1 poly2_lay.setFactorySkillLayer(""); // Polysilicon-2 activeLayers[P_TYPE].setFactorySkillLayer("aa"); // P-Active activeLayers[N_TYPE].setFactorySkillLayer("aa"); // N-Active selectLayers[P_TYPE].setFactorySkillLayer("pplus"); // P-Select selectLayers[N_TYPE].setFactorySkillLayer("nplus"); // N-Select wellLayers[P_TYPE].setFactorySkillLayer("pwell"); // P-Well wellLayers[N_TYPE].setFactorySkillLayer("nwell"); // N-Well polyCutLayer.setFactorySkillLayer("pcont"); // Poly-Cut activeCut_lay.setFactorySkillLayer("acont"); // Active-Cut via1_lay.setFactorySkillLayer("via"); // Via-1 via2_lay.setFactorySkillLayer("via2"); // Via-2 via3_lay.setFactorySkillLayer("via3"); // Via-3 via4_lay.setFactorySkillLayer("via4"); // Via-4 via5_lay.setFactorySkillLayer("via5"); // Via-5 passivation_lay.setFactorySkillLayer("glasscut"); // Passivation transistorPoly_lay.setFactorySkillLayer("poly"); // Transistor-Poly polyCap_lay.setFactorySkillLayer(""); // Poly-Cap pActiveWell_lay.setFactorySkillLayer("aa"); // P-Active-Well silicideBlock_lay.setFactorySkillLayer(""); // Silicide-Block thickActive_lay.setFactorySkillLayer(""); // Thick-Active pseudoMetal1_lay.setFactorySkillLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactorySkillLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactorySkillLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactorySkillLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactorySkillLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactorySkillLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactorySkillLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactorySkillLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactorySkillLayer("pplus"); // Pseudo-P-Select pseudoNSelect_lay.setFactorySkillLayer("nplus"); // Pseudo-N-Select pseudoPWell_lay.setFactorySkillLayer("pwell"); // Pseudo-P-Well pseudoNWell_lay.setFactorySkillLayer("nwell"); // Pseudo-N-Well padFrame_lay.setFactorySkillLayer(""); // Pad-Frame // The layer distance // Data base on 18nm technology with 200nm as grid unit. double BULK_LAYER = 10; double DIFF_LAYER = 1; // dummy distance for now 0.2/0.2 double ILD_LAYER = 3.5; // 0.7/0.2 convertLength() double IMD_LAYER = 5.65; // 1.13um/0.2 double METAL_LAYER = 2.65; // 0.53um/0.2 activeLayers[P_TYPE].setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active 0.17um/0.2 = activeLayers[N_TYPE].setFactory3DInfo(0.8, BULK_LAYER + 2*DIFF_LAYER); // N-Active 0.16um/0.2 selectLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // P-Select selectLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // N-Select wellLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // P-Well wellLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // N-Well pActiveWell_lay.setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active-Well thickActive_lay.setFactory3DInfo(0.5, BULK_LAYER + 0.5); // Thick Active (between select and well) metalLayers[0].setFactory3DInfo(METAL_LAYER, ILD_LAYER + activeLayers[P_TYPE].getDepth()); // Metal-1 0.53um/0.2 metalLayers[1].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[0].getDistance()); // Metal-2 via1_lay.setFactory3DInfo(metalLayers[1].getDistance()-metalLayers[0].getDepth(), metalLayers[0].getDepth()); // Via-1 metalLayers[2].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[1].getDistance()); // Metal-3 via2_lay.setFactory3DInfo(metalLayers[2].getDistance()-metalLayers[1].getDepth(), metalLayers[1].getDepth()); // Via-2 metalLayers[3].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[2].getDistance()); // Metal-4 via3_lay.setFactory3DInfo(metalLayers[3].getDistance()-metalLayers[2].getDepth(), metalLayers[2].getDepth()); // Via-3 metalLayers[4].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[3].getDistance()); // Metal-5 via4_lay.setFactory3DInfo(metalLayers[4].getDistance()-metalLayers[3].getDepth(), metalLayers[3].getDepth()); // Via-4 metalLayers[5].setFactory3DInfo(4.95, IMD_LAYER + metalLayers[4].getDistance()); // Metal-6 0.99um/0.2 via5_lay.setFactory3DInfo(metalLayers[5].getDistance()-metalLayers[4].getDepth(), metalLayers[4].getDepth()); // Via-5 double PASS_LAYER = 5; // 1um/0.2 double PO_LAYER = 1; // 0.2/0.2 double FOX_LAYER = 1.75; // 0.35/0.2 double TOX_LAYER = 0; // Very narrow thin oxide in gate /* for displaying pins */ pseudoMetal1_lay.setFactory3DInfo(0, metalLayers[0].getDistance()); // Pseudo-Metal-1 pseudoMetal2_lay.setFactory3DInfo(0, metalLayers[1].getDistance()); // Pseudo-Metal-2 pseudoMetal3_lay.setFactory3DInfo(0, metalLayers[2].getDistance()); // Pseudo-Metal-3 pseudoMetal4_lay.setFactory3DInfo(0, metalLayers[3].getDistance()); // Pseudo-Metal-4 pseudoMetal5_lay.setFactory3DInfo(0, metalLayers[4].getDistance()); // Pseudo-Metal-5 pseudoMetal6_lay.setFactory3DInfo(0, metalLayers[5].getDistance()); // Pseudo-Metal-6 // Poly layers poly1_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Polysilicon-1 transistorPoly_lay.setFactory3DInfo(PO_LAYER, TOX_LAYER + activeLayers[P_TYPE].getDepth()); // Transistor-Poly poly2_lay.setFactory3DInfo(PO_LAYER, transistorPoly_lay.getDepth()); // Polysilicon-2 // on top of transistor layer? polyCap_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Poly-Cap @TODO GVG Ask polyCap polyCutLayer.setFactory3DInfo(metalLayers[0].getDistance()-poly1_lay.getDepth(), poly1_lay.getDepth()); // Poly-Cut between poly and metal1 activeCut_lay.setFactory3DInfo(metalLayers[0].getDistance()-activeLayers[N_TYPE].getDepth(), activeLayers[N_TYPE].getDepth()); // Active-Cut betweent active and metal1 // Other layers passivation_lay.setFactory3DInfo(PASS_LAYER, metalLayers[5].getDepth()); // Passivation silicideBlock_lay.setFactory3DInfo(0, BULK_LAYER); // Silicide-Block padFrame_lay.setFactory3DInfo(0, passivation_lay.getDepth()); // Pad-Frame pseudoPoly1_lay.setFactory3DInfo(0, poly1_lay.getDistance()); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactory3DInfo(0, poly2_lay.getDistance()); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactory3DInfo(0, activeLayers[P_TYPE].getDistance()); // Pseudo-P-Active pseudoNActive_lay.setFactory3DInfo(0, activeLayers[N_TYPE].getDistance()); // Pseudo-N-Active pseudoPSelect_lay.setFactory3DInfo(0, selectLayers[P_TYPE].getDistance()); // Pseudo-P-Select pseudoNSelect_lay.setFactory3DInfo(0, selectLayers[N_TYPE].getDistance()); // Pseudo-N-Select pseudoPWell_lay.setFactory3DInfo(0, wellLayers[P_TYPE].getDistance()); // Pseudo-P-Well pseudoNWell_lay.setFactory3DInfo(0, wellLayers[N_TYPE].getDistance()); // Pseudo-N-Well // The Spice parasitics metalLayers[0].setFactoryParasitics(0.06, 0.07, 0); // Metal-1 metalLayers[1].setFactoryParasitics(0.06, 0.04, 0); // Metal-2 metalLayers[2].setFactoryParasitics(0.06, 0.04, 0); // Metal-3 metalLayers[3].setFactoryParasitics(0.03, 0.04, 0); // Metal-4 metalLayers[4].setFactoryParasitics(0.03, 0.04, 0); // Metal-5 metalLayers[5].setFactoryParasitics(0.03, 0.04, 0); // Metal-6 poly1_lay.setFactoryParasitics(2.5, 0.09, 0); // Polysilicon-1 poly2_lay.setFactoryParasitics(50.0, 1.0, 0); // Polysilicon-2 activeLayers[P_TYPE].setFactoryParasitics(2.5, 0.9, 0); // P-Active activeLayers[N_TYPE].setFactoryParasitics(3.0, 0.9, 0); // N-Active selectLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Select selectLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Select wellLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Well wellLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Well polyCutLayer.setFactoryParasitics(2.2, 0, 0); // Poly-Cut activeCut_lay.setFactoryParasitics(2.5, 0, 0); // Active-Cut via1_lay.setFactoryParasitics(1.0, 0, 0); // Via-1 via2_lay.setFactoryParasitics(0.9, 0, 0); // Via-2 via3_lay.setFactoryParasitics(0.8, 0, 0); // Via-3 via4_lay.setFactoryParasitics(0.8, 0, 0); // Via-4 via5_lay.setFactoryParasitics(0.8, 0, 0); // Via-5 passivation_lay.setFactoryParasitics(0, 0, 0); // Passivation transistorPoly_lay.setFactoryParasitics(2.5, 0.09, 0); // Transistor-Poly polyCap_lay.setFactoryParasitics(0, 0, 0); // Poly-Cap pActiveWell_lay.setFactoryParasitics(0, 0, 0); // P-Active-Well silicideBlock_lay.setFactoryParasitics(0, 0, 0); // Silicide-Block thickActive_lay.setFactoryParasitics(0, 0, 0); // Thick-Active pseudoMetal1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Active pseudoNActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Active pseudoPSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Select pseudoNSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Select pseudoPWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Well pseudoNWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Well padFrame_lay.setFactoryParasitics(0, 0, 0); // Pad-Frame setFactoryParasitics(50, 0.04); String [] headerLevel1 = { "*CMOS/BULK-NWELL (PRELIMINARY PARAMETERS)", ".OPTIONS NOMOD DEFL=3UM DEFW=3UM DEFAD=70P DEFAS=70P LIMPTS=1000", "+ITL5=0 RELTOL=0.01 ABSTOL=500PA VNTOL=500UV LVLTIM=2", "+LVLCOD=1", ".MODEL N NMOS LEVEL=1", "+KP=60E-6 VTO=0.7 GAMMA=0.3 LAMBDA=0.05 PHI=0.6", "+LD=0.4E-6 TOX=40E-9 CGSO=2.0E-10 CGDO=2.0E-10 CJ=.2MF/M^2", ".MODEL P PMOS LEVEL=1", "+KP=20E-6 VTO=0.7 GAMMA=0.4 LAMBDA=0.05 PHI=0.6", "+LD=0.6E-6 TOX=40E-9 CGSO=3.0E-10 CGDO=3.0E-10 CJ=.2MF/M^2", ".MODEL DIFFCAP D CJO=.2MF/M^2" }; setSpiceHeaderLevel1(headerLevel1); String [] headerLevel2 = { "* MOSIS 3u CMOS PARAMS", ".OPTIONS NOMOD DEFL=2UM DEFW=6UM DEFAD=100P DEFAS=100P", "+LIMPTS=1000 ITL5=0 ABSTOL=500PA VNTOL=500UV", "* Note that ITL5=0 sets ITL5 to infinity", ".MODEL N NMOS LEVEL=2 LD=0.3943U TOX=502E-10", "+NSUB=1.22416E+16 VTO=0.756 KP=4.224E-05 GAMMA=0.9241", "+PHI=0.6 UO=623.661 UEXP=8.328627E-02 UCRIT=54015.0", "+DELTA=5.218409E-03 VMAX=50072.2 XJ=0.4U LAMBDA=2.975321E-02", "+NFS=4.909947E+12 NEFF=1.001E-02 NSS=0.0 TPG=1.0", "+RSH=20.37 CGDO=3.1E-10 CGSO=3.1E-10", "+CJ=3.205E-04 MJ=0.4579 CJSW=4.62E-10 MJSW=0.2955 PB=0.7", ".MODEL P PMOS LEVEL=2 LD=0.2875U TOX=502E-10", "+NSUB=1.715148E+15 VTO=-0.7045 KP=1.686E-05 GAMMA=0.3459", "+PHI=0.6 UO=248.933 UEXP=1.02652 UCRIT=182055.0", "+DELTA=1.0E-06 VMAX=100000.0 XJ=0.4U LAMBDA=1.25919E-02", "+NFS=1.0E+12 NEFF=1.001E-02 NSS=0.0 TPG=-1.0", "+RSH=79.10 CGDO=2.89E-10 CGSO=2.89E-10", "+CJ=1.319E-04 MJ=0.4125 CJSW=3.421E-10 MJSW=0.198 PB=0.66", ".TEMP 25.0" }; setSpiceHeaderLevel2(headerLevel2); //**************************************** ARCS **************************************** /** metal 1 arc */ metalArcs[0] = ArcProto.newInstance(this, "Metal-1", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[0], 0, Poly.Type.FILLED) }); metalArcs[0].setFunction(ArcProto.Function.METAL1); metalArcs[0].setFactoryFixedAngle(true); metalArcs[0].setWipable(); metalArcs[0].setFactoryAngleIncrement(90); /** metal 2 arc */ metalArcs[1] = ArcProto.newInstance(this, "Metal-2", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[1], 0, Poly.Type.FILLED) }); metalArcs[1].setFunction(ArcProto.Function.METAL2); metalArcs[1].setFactoryFixedAngle(true); metalArcs[1].setWipable(); metalArcs[1].setFactoryAngleIncrement(90); /** metal 3 arc */ metalArcs[2] = ArcProto.newInstance(this, "Metal-3", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[2], 0, Poly.Type.FILLED) }); metalArcs[2].setFunction(ArcProto.Function.METAL3); metalArcs[2].setFactoryFixedAngle(true); metalArcs[2].setWipable(); metalArcs[2].setFactoryAngleIncrement(90); /** metal 4 arc */ metalArcs[3] = ArcProto.newInstance(this, "Metal-4", 6.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[3], 0, Poly.Type.FILLED) }); metalArcs[3].setFunction(ArcProto.Function.METAL4); metalArcs[3].setFactoryFixedAngle(true); metalArcs[3].setWipable(); metalArcs[3].setFactoryAngleIncrement(90); /** metal 5 arc */ metalArcs[4] = ArcProto.newInstance(this, "Metal-5", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[4], 0, Poly.Type.FILLED) }); metalArcs[4].setFunction(ArcProto.Function.METAL5); metalArcs[4].setFactoryFixedAngle(true); metalArcs[4].setWipable(); metalArcs[4].setFactoryAngleIncrement(90); /** metal 6 arc */ metalArcs[5] = ArcProto.newInstance(this, "Metal-6", 4.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[5], 0, Poly.Type.FILLED) }); metalArcs[5].setFunction(ArcProto.Function.METAL6); metalArcs[5].setFactoryFixedAngle(true); metalArcs[5].setWipable(); metalArcs[5].setFactoryAngleIncrement(90); /** polysilicon 1 arc */ poly1_arc = ArcProto.newInstance(this, "Polysilicon-1", 2.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly1_lay, 0, Poly.Type.FILLED) }); poly1_arc.setFunction(ArcProto.Function.POLY1); poly1_arc.setFactoryFixedAngle(true); poly1_arc.setWipable(); poly1_arc.setFactoryAngleIncrement(90); /** polysilicon 2 arc */ poly2_arc = ArcProto.newInstance(this, "Polysilicon-2", 7.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly2_lay, 0, Poly.Type.FILLED) }); poly2_arc.setFunction(ArcProto.Function.POLY2); poly2_arc.setFactoryFixedAngle(true); poly2_arc.setWipable(); poly2_arc.setFactoryAngleIncrement(90); poly2_arc.setNotUsed(); /** P-active arc */ activeArcs[P_TYPE] = ArcProto.newInstance(this, "P-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[P_TYPE], 8, Poly.Type.FILLED) }); activeArcs[P_TYPE].setFunction(ArcProto.Function.DIFFP); activeArcs[P_TYPE].setFactoryFixedAngle(true); activeArcs[P_TYPE].setWipable(); activeArcs[P_TYPE].setFactoryAngleIncrement(90); activeArcs[P_TYPE].setWidthOffset(12.0); /** N-active arc */ activeArcs[N_TYPE] = ArcProto.newInstance(this, "N-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[N_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[N_TYPE], 8, Poly.Type.FILLED) }); activeArcs[N_TYPE].setFunction(ArcProto.Function.DIFFN); activeArcs[N_TYPE].setFactoryFixedAngle(true); activeArcs[N_TYPE].setWipable(); activeArcs[N_TYPE].setFactoryAngleIncrement(90); activeArcs[N_TYPE].setWidthOffset(12.0); /** General active arc */ active_arc = ArcProto.newInstance(this, "Active", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED) }); active_arc.setFunction(ArcProto.Function.DIFF); active_arc.setFactoryFixedAngle(true); active_arc.setWipable(); active_arc.setFactoryAngleIncrement(90); active_arc.setNotUsed(); //**************************************** NODES **************************************** /** metal-1-pin */ metalPinNodes[0] = PrimitiveNode.newInstance("Metal-1-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[0], new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[0].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[0].setArcsWipe(); metalPinNodes[0].setArcsShrink(); /** metal-2-pin */ metalPinNodes[1] = PrimitiveNode.newInstance("Metal-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[1], new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[1].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[1].setArcsWipe(); metalPinNodes[1].setArcsShrink(); /** metal-3-pin */ metalPinNodes[2] = PrimitiveNode.newInstance("Metal-3-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal3_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[2], new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[2].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[2].setArcsWipe(); metalPinNodes[2].setArcsShrink(); /** metal-4-pin */ metalPinNodes[3] = PrimitiveNode.newInstance("Metal-4-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal4_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[3], new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[3].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[3].setArcsWipe(); metalPinNodes[3].setArcsShrink(); /** metal-5-pin */ metalPinNodes[4] = PrimitiveNode.newInstance("Metal-5-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal5_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[4], new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[4].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[4].setArcsWipe(); metalPinNodes[4].setArcsShrink(); metalPinNodes[4].setNotUsed(); /** metal-6-pin */ metalPinNodes[5] = PrimitiveNode.newInstance("Metal-6-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal6_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[5].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[5], new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[5].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[5].setArcsWipe(); metalPinNodes[5].setArcsShrink(); metalPinNodes[5].setNotUsed(); /** polysilicon-1-pin */ poly1Pin_node = PrimitiveNode.newInstance("Polysilicon-1-Pin", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Pin_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Pin_node.setFunction(PrimitiveNode.Function.PIN); poly1Pin_node.setArcsWipe(); poly1Pin_node.setArcsShrink(); /** polysilicon-2-pin */ poly2Pin_node = PrimitiveNode.newInstance("Polysilicon-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Pin_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Pin_node.setFunction(PrimitiveNode.Function.PIN); poly2Pin_node.setArcsWipe(); poly2Pin_node.setArcsShrink(); poly2Pin_node.setNotUsed(); /** P-active-pin */ activePinNodes[P_TYPE] = PrimitiveNode.newInstance("P-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoNWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoPSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE]}, "p-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[P_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[P_TYPE].setArcsWipe(); activePinNodes[P_TYPE].setArcsShrink(); /** N-active-pin */ activePinNodes[N_TYPE] = PrimitiveNode.newInstance("N-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoPWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE]}, "n-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[N_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[N_TYPE].setArcsWipe(); activePinNodes[N_TYPE].setArcsShrink(); /** General active-pin */ activePin_node = PrimitiveNode.newInstance("Active-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activePin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePin_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); activePin_node.setFunction(PrimitiveNode.Function.PIN); activePin_node.setArcsWipe(); activePin_node.setArcsShrink(); activePin_node.setNotUsed(); /** metal-1-P-active-contact */ metalActiveContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX,Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "metal-1-p-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[P_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-N-active-contact */ metalActiveContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "metal-1-n-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[N_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-polysilicon-1-contact */ metal1Poly1Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-Con", this, 5.0, 5.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metal1Poly1Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly1Contact_node, new ArcProto[] {poly1_arc, metalArcs[0]}, "metal-1-polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2), EdgeV.fromBottom(2), EdgeH.fromRight(2), EdgeV.fromTop(2)) }); metal1Poly1Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly1Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly1Contact_node.setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metal1Poly1Contact_node.setMinSize(5, 5, "5.2, 7.3"); /** metal-1-polysilicon-2-contact */ metal1Poly2Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-2-Con", this, 10.0, 10.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); metal1Poly2Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly2Contact_node, new ArcProto[] {poly2_arc, metalArcs[0]}, "metal-1-polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4.5), EdgeV.fromBottom(4.5), EdgeH.fromRight(4.5), EdgeV.fromTop(4.5)) }); metal1Poly2Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly2Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly2Contact_node.setSpecialValues(new double [] {2, 2, 4, 4, 3, 3}); metal1Poly2Contact_node.setNotUsed(); metal1Poly2Contact_node.setMinSize(10, 10, "?"); /** metal-1-polysilicon-1-2-contact */ metal1Poly12Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-2-Con", this, 15.0, 15.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)) }); metal1Poly12Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly12Contact_node, new ArcProto[] {poly1_arc, poly2_arc, metalArcs[0]}, "metal-1-polysilicon-1-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7), EdgeV.fromBottom(7), EdgeH.fromRight(7), EdgeV.fromTop(7)) }); metal1Poly12Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly12Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly12Contact_node.setSpecialValues(new double [] {2, 2, 6.5, 6.5, 3, 3}); metal1Poly12Contact_node.setNotUsed(); metal1Poly12Contact_node.setMinSize(15, 15, "?"); /** P-Transistor */ /** N-Transistor */ String[] stdNames = {"p", "n"}; for (int i = 0; i < 2; i++) { transistorPolyLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyLLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyRLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyCLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorActiveLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveTLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveBLayers[i] = new Technology.NodeLayer(activeLayers[i], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10))}, 4, 4, 0, 0); transistorWellLayers[i] = new Technology.NodeLayer(wellLayers[(i+1)%transistorNodes.length], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); transistorSelectLayers[i] = new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(5)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(5))}, 6, 6, 2, 2); transistorNodes[i] = PrimitiveNode.newInstance(stdNames[i].toUpperCase()+"-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {transistorActiveLayers[i], transistorPolyLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {transistorActiveTLayers[i], transistorActiveBLayers[i], transistorPolyCLayers[i], transistorPolyLLayers[i], transistorPolyRLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); transistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); transistorNodes[i].setHoldsOutline(); transistorNodes[i].setCanShrink(); transistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); transistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); transistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); } /** Thick oxide transistors */ String[] thickNames = {"Thick-P", "Thick-N"}; Technology.NodeLayer[] thickActiveLayers = new Technology.NodeLayer[] {transistorActiveLayers[P_TYPE], transistorActiveLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLayers = new Technology.NodeLayer[] {transistorPolyLayers[P_TYPE], transistorPolyLayers[N_TYPE]}; Technology.NodeLayer[] thickWellLayers = new Technology.NodeLayer[] {transistorWellLayers[P_TYPE], transistorWellLayers[N_TYPE]}; Technology.NodeLayer[] thickSelectLayers = new Technology.NodeLayer[] {transistorSelectLayers[P_TYPE], transistorSelectLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveTLayers = new Technology.NodeLayer[] {transistorActiveTLayers[P_TYPE], transistorActiveTLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveBLayers = new Technology.NodeLayer[] {transistorActiveBLayers[P_TYPE], transistorActiveBLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyCLayers = new Technology.NodeLayer[] {transistorPolyCLayers[P_TYPE], transistorPolyCLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLLayers = new Technology.NodeLayer[] {transistorPolyLLayers[P_TYPE], transistorPolyLLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyRLayers = new Technology.NodeLayer[] {transistorPolyRLayers[P_TYPE], transistorPolyRLayers[N_TYPE]}; Technology.NodeLayer[] thickLayers = new Technology.NodeLayer[2]; for (int i = 0; i < thickLayers.length; i++) { thickLayers[i] = new Technology.NodeLayer(thickActive_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); } for (int i = 0; i < thickTransistorNodes.length; i++) { thickTransistorNodes[i] = PrimitiveNode.newInstance(thickNames[i] + "-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {thickActiveLayers[i], thickPolyLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {thickActiveTLayers[i], thickActiveBLayers[i], thickPolyCLayers[i], thickPolyLLayers[i], thickPolyRLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); thickTransistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); thickTransistorNodes[i].setHoldsOutline(); thickTransistorNodes[i].setCanShrink(); thickTransistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); thickTransistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); thickTransistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); thickTransistorNodes[i].setSpecialNode(); // For display purposes } /** Scalable-P-Transistor */ scalableTransistorNodes[P_TYPE] = PrimitiveNode.newInstance("P-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[P_TYPE].setFunction(PrimitiveNode.Function.TRAPMOS); scalableTransistorNodes[P_TYPE].setCanShrink(); scalableTransistorNodes[P_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** Scalable-N-Transistor */ scalableTransistorNodes[N_TYPE] = PrimitiveNode.newInstance("N-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[N_TYPE].setFunction(PrimitiveNode.Function.TRANMOS); scalableTransistorNodes[N_TYPE].setCanShrink(); scalableTransistorNodes[N_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** metal-1-metal-2-contact */ metalContactNodes[0] = PrimitiveNode.newInstance("Metal-1-Metal-2-Con", this, 5.0, 5.0, new SizeOffset(0.5, 0.5, 0.5, 0.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metalContactNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[0], new ArcProto[] {metalArcs[0], metalArcs[1]}, "metal-1-metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalContactNodes[0].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[0].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[0].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[0].setMinSize(5, 5, "8.3, 9.3"); /** metal-2-metal-3-contact */ metalContactNodes[1] = PrimitiveNode.newInstance("Metal-2-Metal-3-Con", this, 6.0, 6.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[1], new ArcProto[] {metalArcs[1], metalArcs[2]}, "metal-2-metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[1].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[1].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[1].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[1].setMinSize(6, 6, "14.3, 15.3"); /** metal-3-metal-4-contact */ metalContactNodes[2] = PrimitiveNode.newInstance("Metal-3-Metal-4-Con", this, 6.0, 6.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[2], new ArcProto[] {metalArcs[2], metalArcs[3]}, "metal-3-metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[2].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[2].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[2].setSpecialValues(new double [] {2, 2, 2, 2, 3, 3}); metalContactNodes[2].setMinSize(6, 6, "21.3, 22.3"); /** metal-4-metal-5-contact */ metalContactNodes[3] = PrimitiveNode.newInstance("Metal-4-Metal-5-Con", this, 7.0, 7.0, new SizeOffset(1.5, 1.5, 1.5, 1.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2.5)) }); metalContactNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[3], new ArcProto[] {metalArcs[3], metalArcs[4]}, "metal-4-metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[3].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[3].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[3].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[3].setNotUsed(); metalContactNodes[3].setMinSize(7, 7, "25.3, 26.3"); /** metal-5-metal-6-contact */ metalContactNodes[4] = PrimitiveNode.newInstance("Metal-5-Metal-6-Con", this, 8.0, 8.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)) }); metalContactNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[4], new ArcProto[] {metalArcs[4], metalArcs[5]}, "metal-5-metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[4].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[4].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[4].setSpecialValues(new double [] {3, 3, 2, 2, 4, 4}); metalContactNodes[4].setNotUsed(); metalContactNodes[4].setMinSize(8, 8, "29.3, 30.3"); /** Metal-1-P-Well Contact */ metalWellContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[P_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.WELL); metalWellContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[P_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /** Metal-1-N-Well Contact */ metalWellContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[N_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-substrate", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.SUBSTRATE); metalWellContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[N_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /********************** RPO Resistor-Node ********************************/ double polySelectOffX = 1.8; /* NP.C.3 */ // double rpoViaOffX = 2.2 /* RPO.C.2 */; double polyCutSize = 2.2; /* page 28 */ double resistorViaOff = 1.0; /* page 28 */ double resistorConW = polyCutSize + 2*resistorViaOff /*contact width viaW + 2*viaS = (2.2 + 2*1). It must be 1xN */; double resistorConH = resistorConW /*contact height*/; double resistorOffX = resistorConW + polySelectOffX + 1.2 /*0.22um-0.1 (poly extension in contact)*/; double resistorW = 20 + 2*resistorOffX; double resistorOffY = 2.2 /* RPO.C.2*/; double resistorH = 2*resistorOffY + resistorConH; // double resistorM1Off = 0.5 /*poly surround in poly contact */; // double resistorPolyOffX = 2.2; /* page 28 */ // double resistorV2OffX = -polyCutSize - 0.7 + resistorPolyX + resistorConW; // double resistorPortOffX = resistorPolyX + (resistorConW-polyCutSize)/2; // for the port double resistorM1Off = resistorViaOff - 0.6; // 0.6 = M.E.2 double resistorM1W = resistorConW-2*resistorM1Off; double resistorM1OffX = resistorM1Off + polySelectOffX; double resistorM1OffY = resistorM1Off + resistorOffY; double resistorV1OffX = resistorViaOff + polySelectOffX; double resistorV1OffY = resistorOffY + (resistorConH-polyCutSize)/2; rpoResistorNodes = new PrimitiveNode[2]; for (int i = 0; i < rpoResistorNodes.length; i++) { rpoResistorNodes[i] = PrimitiveNode.newInstance(stdNames[i]+"-Poly-RPO-Resistor", this, resistorW, resistorH, new SizeOffset(resistorOffX, resistorOffX, resistorOffY, resistorOffY), new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(polySelectOffX), EdgeV.fromBottom(resistorOffY)), new Technology.TechPoint(EdgeH.fromRight(polySelectOffX), EdgeV.fromTop(resistorOffY))}), new Technology.NodeLayer(silicideBlock_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorOffX), EdgeV.makeBottomEdge()), new Technology.TechPoint(EdgeH.fromRight(resistorOffX), EdgeV.makeTopEdge())}), new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(0.2)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(0.2))}), // Left contact new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX+resistorM1W), EdgeV.fromTop(resistorM1OffY))}), // left via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}), // Right contact new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX+resistorM1W), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX), EdgeV.fromTop(resistorM1OffY))}), // right via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}) }); rpoResistorNodes[i].addPrimitivePorts(new PrimitivePort [] { // left port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "left-rpo", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)), // right port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "right-rpo", 0,180, 1, PortCharacteristic.UNKNOWN, EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)) }); rpoResistorNodes[i].setFunction(PrimitiveNode.Function.PRESIST); rpoResistorNodes[i].setHoldsOutline(); rpoResistorNodes[i].setSpecialType(PrimitiveNode.POLYGONAL); } /** Metal-1-Node */ metal1Node_node = PrimitiveNode.newInstance("Metal-1-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Node_node, new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal1Node_node.setFunction(PrimitiveNode.Function.NODE); metal1Node_node.setHoldsOutline(); metal1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-2-Node */ metal2Node_node = PrimitiveNode.newInstance("Metal-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal2Node_node, new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal2Node_node.setFunction(PrimitiveNode.Function.NODE); metal2Node_node.setHoldsOutline(); metal2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-3-Node */ metal3Node_node = PrimitiveNode.newInstance("Metal-3-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal3Node_node, new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal3Node_node.setFunction(PrimitiveNode.Function.NODE); metal3Node_node.setHoldsOutline(); metal3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-4-Node */ metal4Node_node = PrimitiveNode.newInstance("Metal-4-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal4Node_node, new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal4Node_node.setFunction(PrimitiveNode.Function.NODE); metal4Node_node.setHoldsOutline(); metal4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-5-Node */ metal5Node_node = PrimitiveNode.newInstance("Metal-5-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal5Node_node, new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal5Node_node.setFunction(PrimitiveNode.Function.NODE); metal5Node_node.setHoldsOutline(); metal5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal5Node_node.setNotUsed(); /** Metal-6-Node */ metal6Node_node = PrimitiveNode.newInstance("Metal-6-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal6Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal6Node_node, new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal6Node_node.setFunction(PrimitiveNode.Function.NODE); metal6Node_node.setHoldsOutline(); metal6Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal6Node_node.setNotUsed(); /** Polysilicon-1-Node */ poly1Node_node = PrimitiveNode.newInstance("Polysilicon-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Node_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Node_node.setFunction(PrimitiveNode.Function.NODE); poly1Node_node.setHoldsOutline(); poly1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-2-Node */ poly2Node_node = PrimitiveNode.newInstance("Polysilicon-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Node_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Node_node.setFunction(PrimitiveNode.Function.NODE); poly2Node_node.setHoldsOutline(); poly2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); poly2Node_node.setNotUsed(); /** P-Active-Node */ pActiveNode_node = PrimitiveNode.newInstance("P-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); pActiveNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveNode_node.setHoldsOutline(); pActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Active-Node */ nActiveNode_node = PrimitiveNode.newInstance("N-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); nActiveNode_node.setFunction(PrimitiveNode.Function.NODE); nActiveNode_node.setHoldsOutline(); nActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Select-Node */ pSelectNode_node = PrimitiveNode.newInstance("P-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pSelectNode_node.setFunction(PrimitiveNode.Function.NODE); pSelectNode_node.setHoldsOutline(); pSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Select-Node */ nSelectNode_node = PrimitiveNode.newInstance("N-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); nSelectNode_node.setFunction(PrimitiveNode.Function.NODE); nSelectNode_node.setHoldsOutline(); nSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** PolyCut-Node */ polyCutNode_node = PrimitiveNode.newInstance("Poly-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCutNode_node, new ArcProto[0], "polycut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCutNode_node.setFunction(PrimitiveNode.Function.NODE); polyCutNode_node.setHoldsOutline(); polyCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** ActiveCut-Node */ activeCutNode_node = PrimitiveNode.newInstance("Active-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activeCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activeCutNode_node, new ArcProto[0], "activecut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); activeCutNode_node.setFunction(PrimitiveNode.Function.NODE); activeCutNode_node.setHoldsOutline(); activeCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-1-Node */ via1Node_node = PrimitiveNode.newInstance("Via-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via1Node_node, new ArcProto[0], "via-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via1Node_node.setFunction(PrimitiveNode.Function.NODE); via1Node_node.setHoldsOutline(); via1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-2-Node */ via2Node_node = PrimitiveNode.newInstance("Via-2-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via2Node_node, new ArcProto[0], "via-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via2Node_node.setFunction(PrimitiveNode.Function.NODE); via2Node_node.setHoldsOutline(); via2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-3-Node */ via3Node_node = PrimitiveNode.newInstance("Via-3-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via3Node_node, new ArcProto[0], "via-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via3Node_node.setFunction(PrimitiveNode.Function.NODE); via3Node_node.setHoldsOutline(); via3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-4-Node */ via4Node_node = PrimitiveNode.newInstance("Via-4-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via4Node_node, new ArcProto[0], "via-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via4Node_node.setFunction(PrimitiveNode.Function.NODE); via4Node_node.setHoldsOutline(); via4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via4Node_node.setNotUsed(); /** Via-5-Node */ via5Node_node = PrimitiveNode.newInstance("Via-5-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via5Node_node, new ArcProto[0], "via-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via5Node_node.setFunction(PrimitiveNode.Function.NODE); via5Node_node.setHoldsOutline(); via5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via5Node_node.setNotUsed(); /** P-Well-Node */ pWellNode_node = PrimitiveNode.newInstance("P-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); pWellNode_node.setFunction(PrimitiveNode.Function.NODE); pWellNode_node.setHoldsOutline(); pWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Well-Node */ nWellNode_node = PrimitiveNode.newInstance("N-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); nWellNode_node.setFunction(PrimitiveNode.Function.NODE); nWellNode_node.setHoldsOutline(); nWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Passivation-Node */ passivationNode_node = PrimitiveNode.newInstance("Passivation-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(passivation_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); passivationNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, passivationNode_node, new ArcProto[0], "passivation", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); passivationNode_node.setFunction(PrimitiveNode.Function.NODE); passivationNode_node.setHoldsOutline(); passivationNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Pad-Frame-Node */ padFrameNode_node = PrimitiveNode.newInstance("Pad-Frame-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(padFrame_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); padFrameNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, padFrameNode_node, new ArcProto[0], "pad-frame", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); padFrameNode_node.setFunction(PrimitiveNode.Function.NODE); padFrameNode_node.setHoldsOutline(); padFrameNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Poly-Cap-Node */ polyCapNode_node = PrimitiveNode.newInstance("Poly-Cap-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCap_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCapNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCapNode_node, new ArcProto[0], "poly-cap", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCapNode_node.setFunction(PrimitiveNode.Function.NODE); polyCapNode_node.setHoldsOutline(); polyCapNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Active-Well-Node */ pActiveWellNode_node = PrimitiveNode.newInstance("P-Active-Well-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveWellNode_node, new ArcProto[0], "p-active-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pActiveWellNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveWellNode_node.setHoldsOutline(); pActiveWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-1-Transistor-Node */ polyTransistorNode_node = PrimitiveNode.newInstance("Transistor-Poly-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyTransistorNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyTransistorNode_node, new ArcProto[] {poly1_arc}, "trans-poly-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); polyTransistorNode_node.setFunction(PrimitiveNode.Function.NODE); polyTransistorNode_node.setHoldsOutline(); polyTransistorNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Silicide-Block-Node */ silicideBlockNode_node = PrimitiveNode.newInstance("Silicide-Block-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(silicideBlock_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); silicideBlockNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, silicideBlockNode_node, new ArcProto[] {poly1_arc}, "silicide-block", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); silicideBlockNode_node.setFunction(PrimitiveNode.Function.NODE); silicideBlockNode_node.setHoldsOutline(); silicideBlockNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Thick-Active-Node */ thickActiveNode_node = PrimitiveNode.newInstance("Thick-Active-Node", this, 4.0, 4.0, null, // 4.0 is given by rule 24.1 new Technology.NodeLayer [] { new Technology.NodeLayer(thickActive_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); thickActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickActiveNode_node, new ArcProto[] {poly1_arc}, "thick-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); thickActiveNode_node.setFunction(PrimitiveNode.Function.NODE); thickActiveNode_node.setHoldsOutline(); thickActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); // The pure layer nodes metalLayers[0].setPureLayerNode(metal1Node_node); // Metal-1 metalLayers[1].setPureLayerNode(metal2Node_node); // Metal-2 metalLayers[2].setPureLayerNode(metal3Node_node); // Metal-3 metalLayers[3].setPureLayerNode(metal4Node_node); // Metal-4 metalLayers[4].setPureLayerNode(metal5Node_node); // Metal-5 metalLayers[5].setPureLayerNode(metal6Node_node); // Metal-6 poly1_lay.setPureLayerNode(poly1Node_node); // Polysilicon-1 poly2_lay.setPureLayerNode(poly2Node_node); // Polysilicon-2 activeLayers[P_TYPE].setPureLayerNode(pActiveNode_node); // P-Active activeLayers[N_TYPE].setPureLayerNode(nActiveNode_node); // N-Active selectLayers[P_TYPE].setPureLayerNode(pSelectNode_node); // P-Select selectLayers[N_TYPE].setPureLayerNode(nSelectNode_node); // N-Select wellLayers[P_TYPE].setPureLayerNode(pWellNode_node); // P-Well wellLayers[N_TYPE].setPureLayerNode(nWellNode_node); // N-Well polyCutLayer.setPureLayerNode(polyCutNode_node); // Poly-Cut activeCut_lay.setPureLayerNode(activeCutNode_node); // Active-Cut via1_lay.setPureLayerNode(via1Node_node); // Via-1 via2_lay.setPureLayerNode(via2Node_node); // Via-2 via3_lay.setPureLayerNode(via3Node_node); // Via-3 via4_lay.setPureLayerNode(via4Node_node); // Via-4 via5_lay.setPureLayerNode(via5Node_node); // Via-5 passivation_lay.setPureLayerNode(passivationNode_node); // Passivation transistorPoly_lay.setPureLayerNode(polyTransistorNode_node); // Transistor-Poly polyCap_lay.setPureLayerNode(polyCapNode_node); // Poly-Cap pActiveWell_lay.setPureLayerNode(pActiveWellNode_node); // P-Active-Well silicideBlock_lay.setPureLayerNode(silicideBlockNode_node); // Silicide-Block thickActive_lay.setPureLayerNode(thickActiveNode_node); // Thick-Active padFrame_lay.setPureLayerNode(padFrameNode_node); // Pad-Frame // Information for palette int maxY = metalArcs.length + activeArcs.length + 1 /* poly*/ + 1 /* trans */ + 1 /*misc*/ + 1 /* well */; nodeGroups = new Object[maxY][3]; int count = 0; String[] shortNames = {"p", "n"}; List tmp; // Transistor nodes first for (int i = 0; i < transistorNodes.length; i++) { tmp = new ArrayList(2); String tmpVar = shortNames[i]+"Mos"; tmp.add(makeNodeInst(transistorNodes[i], transistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(thickTransistorNodes[i], thickTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(scalableTransistorNodes[i], scalableTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); nodeGroups[count][i+1] = tmp; } // Well second count++; for (int i = 0; i < metalWellContactNodes.length; i++) { String tmpVar = shortNames[i]+"Well"; nodeGroups[count][i+1] = makeNodeInst(metalWellContactNodes[i], metalWellContactNodes[i].getFunction(), 0, true, tmpVar, 5.5); } // RPO resistors for (int i = 0; i < rpoResistorNodes.length; i++) { String tmpVar = shortNames[i]+"R"; tmp = new ArrayList(1); tmp.add(makeNodeInst(rpoResistorNodes[i], rpoResistorNodes[i].getFunction(), 0, true, tmpVar, 10)); nodeGroups[i][0] = tmp; } // Active/Well first for (int i = 0; i < activeArcs.length; i++) { nodeGroups[++count][0] = activeArcs[i]; nodeGroups[count][1] = activePinNodes[i]; String tmpVar = shortNames[i]+"Act"; nodeGroups[count][2] = makeNodeInst(metalActiveContactNodes[i], metalActiveContactNodes[i].getFunction(), 0, true, tmpVar, 5.55); } // Poly-related node insts nodeGroups[++count][0] = poly1_arc; nodeGroups[count][1] = poly1Pin_node; nodeGroups[count][2] = metal1Poly1Contact_node; // MXMY contacts for (int i = 0; i < metalArcs.length; i++) { nodeGroups[++count][0] = metalArcs[i]; nodeGroups[count][1] = metalPinNodes[i]; nodeGroups[count][2] = (i < metalArcs.length - 1) ? metalContactNodes[i] : null; } // On the side nodeGroups[++count][0] = "Pure"; nodeGroups[count][1] = "Misc."; nodeGroups[count][2] = "Cell"; }
private MoCMOS() { super("mocmos"); setTechShortName("MOSIS CMOS"); setTechDesc("MOSIS CMOS"); setFactoryScale(200, true); // in nanometers: really 0.2 micron setNoNegatedArcs(); setStaticTechnology(); setFactoryTransparentLayers(new Color [] { new Color( 96,209,255), // Metal-1 new Color(255,155,192), // Polysilicon-1 new Color(107,226, 96), // Active new Color(224, 95,255), // Metal-2 new Color(247,251, 20) // Metal-3 }); setFactoryResolution(0.01); // value in lambdas 0.005um -> 0.05 lambdas foundries.add(new Foundry(Foundry.MOSIS_FOUNDRY, DRCTemplate.MOSIS)); foundries.add(new Foundry("TSMC", DRCTemplate.TSMC)); setFactorySelecedFound(Foundry.MOSIS_FOUNDRY); // default //**************************************** LAYERS **************************************** Layer[] metalLayers = new Layer[6]; // 1 -> 6 /** metal-1 layer */ metalLayers[0] = Layer.newInstance(this, "Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-2 layer */ metalLayers[1] = Layer.newInstance(this, "Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** metal-3 layer */ metalLayers[2] = Layer.newInstance(this, "Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** metal-4 layer */ metalLayers[3] = Layer.newInstance(this, "Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** metal-5 layer */ metalLayers[4] = Layer.newInstance(this, "Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** metal-6 layer */ metalLayers[5] = Layer.newInstance(this, "Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** poly layer */ poly1_lay = Layer.newInstance(this, "Polysilicon-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly2 layer */ Layer poly2_lay = Layer.newInstance(this, "Polysilicon-2", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X Layer[] activeLayers = new Layer[2]; /** P active layer */ activeLayers[P_TYPE] = Layer.newInstance(this, "P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** N active layer */ activeLayers[N_TYPE] = Layer.newInstance(this, "N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 0.5,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX Layer[] selectLayers = new Layer[2]; /** P Select layer */ selectLayers[P_TYPE] = Layer.newInstance(this, "P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** N Select layer */ selectLayers[N_TYPE] = Layer.newInstance(this, "N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 0.2,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// Layer[] wellLayers = new Layer[2]; /** P Well layer */ wellLayers[P_TYPE] = Layer.newInstance(this, "P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** N Well implant */ wellLayers[N_TYPE] = Layer.newInstance(this, "N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 0.2,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** poly cut layer */ Layer polyCutLayer = Layer.newInstance(this, "Poly-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** active cut layer */ Layer activeCut_lay = Layer.newInstance(this, "Active-Cut", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 100,100,100, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via1 layer */ Layer via1_lay = Layer.newInstance(this, "Via1", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via2 layer */ Layer via2_lay = Layer.newInstance(this, "Via2", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via3 layer */ Layer via3_lay = Layer.newInstance(this, "Via3", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via4 layer */ Layer via4_lay = Layer.newInstance(this, "Via4", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** via5 layer */ Layer via5_lay = Layer.newInstance(this, "Via5", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 180,180,180, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** passivation layer */ Layer passivation_lay = Layer.newInstance(this, "Passivation", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 100,100,100, 1.0,true, new int[] { 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000, // 0x1C1C, // XXX XXX 0x3E3E, // XXXXX XXXXX 0x3636, // XX XX XX XX 0x3E3E, // XXXXX XXXXX 0x1C1C, // XXX XXX 0x0000, // 0x0000, // 0x0000}));// /** poly/trans layer */ transistorPoly_lay = Layer.newInstance(this, "Transistor-Poly", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 0.5,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** poly cap layer */ Layer polyCap_lay = Layer.newInstance(this, "Poly-Cap", new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 0,0,0, 1.0,true, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); /** P act well layer */ Layer pActiveWell_lay = Layer.newInstance(this, "P-Active-Well", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,false, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** Silicide block */ /** Resist Protection Oxide (RPO) Same graphics as in 90nm tech */ Layer silicideBlock_lay = Layer.newInstance(this, "Silicide-Block", // new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 230,230,230, 1.0,false, // new int[] { 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000, // // 0x2222, // X X X X // 0x0000, // // 0x8888, // X X X X // 0x0000}));// new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 192,255,255, 0.5,true, new int[] { 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000, /* */ 0x1010, /* X X */ 0x2828, /* X X X X */ 0x4444, /* X X X X */ 0x8282, /* X X X X */ 0x0101, /* X X */ 0x0000, /* */ 0x0000, /* */ 0x0000}));/* */ /** Thick active */ Layer thickActive_lay = Layer.newInstance(this, "Thick-Active", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,0,0, 1.0,false, new int[] { 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020}));// X X /** pseudo metal 1 */ Layer pseudoMetal1_lay = Layer.newInstance(this, "Pseudo-Metal-1", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_1, 96,209,255, 0.8,true, new int[] { 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000, // 0x2222, // X X X X 0x0000, // 0x8888, // X X X X 0x0000}));// /** pseudo metal-2 */ Layer pseudoMetal2_lay = Layer.newInstance(this, "Pseudo-Metal-2", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_4, 224,95,255, 0.7,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-3 */ Layer pseudoMetal3_lay = Layer.newInstance(this, "Pseudo-Metal-3", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_5, 247,251,20, 0.6,true, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo metal-4 */ Layer pseudoMetal4_lay = Layer.newInstance(this, "Pseudo-Metal-4", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 150,150,255, 0.5,true, new int[] { 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000, // 0xFFFF, // XXXXXXXXXXXXXXXX 0x0000}));// /** pseudo metal-5 */ Layer pseudoMetal5_lay = Layer.newInstance(this, "Pseudo-Metal-5", new EGraphics(EGraphics.OUTLINEPAT, EGraphics.OUTLINEPAT, 0, 255,190,6, 0.4,true, new int[] { 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444, // X X X X 0x8888, // X X X X 0x1111, // X X X X 0x2222, // X X X X 0x4444}));// X X X X /** pseudo metal-6 */ Layer pseudoMetal6_lay = Layer.newInstance(this, "Pseudo-Metal-6", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 0,255,255, 0.3,true, new int[] { 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111, // X X X X 0x8888, // X X X X 0x4444, // X X X X 0x2222, // X X X X 0x1111}));// X X X X /** pseudo poly layer */ Layer pseudoPoly1_lay = Layer.newInstance(this, "Pseudo-Polysilicon", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_2, 255,155,192, 1.0,true, new int[] { 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555, // X X X X X X X X 0x1111, // X X X X 0xFFFF, // XXXXXXXXXXXXXXXX 0x1111, // X X X X 0x5555}));// X X X X X X X X /** pseudo poly2 layer */ Layer pseudoPoly2_lay = Layer.newInstance(this, "Pseudo-Electrode", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,190,6, 1.0,true, new int[] { 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888, // X X X X 0xAFAF, // X X XXXXX X XXXX 0x8888, // X X X X 0xFAFA, // XXXXX X XXXXX X 0x8888}));// X X X X /** pseudo P active */ Layer pseudoPActive_lay = Layer.newInstance(this, "Pseudo-P-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo N active */ Layer pseudoNActive_lay = Layer.newInstance(this, "Pseudo-N-Active", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, EGraphics.TRANSPARENT_3, 107,226,96, 1.0,true, new int[] { 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030, // XX XX 0x0000, // 0x0303, // XX XX 0x4848, // X X X X 0x0303, // XX XX 0x0000, // 0x3030, // XX XX 0x8484, // X X X X 0x3030}));// XX XX /** pseudo P Select */ Layer pseudoPSelect_lay = Layer.newInstance(this, "Pseudo-P-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808, // X X 0x1010, // X X 0x2020, // X X 0x4040, // X X 0x8080, // X X 0x0101, // X X 0x0202, // X X 0x0404, // X X 0x0808}));// X X /** pseudo N Select */ Layer pseudoNSelect_lay = Layer.newInstance(this, "Pseudo-N-Select", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 255,255,0, 1.0,false, new int[] { 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000, // 0x0101, // X X 0x0000, // 0x1010, // X X 0x0000}));// /** pseudo P Well */ Layer pseudoPWell_lay = Layer.newInstance(this, "Pseudo-P-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404, // X X 0x0202, // X X 0x0101, // X X 0x8080, // X X 0x4040, // X X 0x2020, // X X 0x1010, // X X 0x0808, // X X 0x0404}));// X X /** pseudo N Well */ Layer pseudoNWell_lay = Layer.newInstance(this, "Pseudo-N-Well", new EGraphics(EGraphics.PATTERNED, EGraphics.PATTERNED, 0, 139,99,46, 1.0,false, new int[] { 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000, // 0x0202, // X X 0x0000, // 0x2020, // X X 0x0000}));// /** pad frame */ Layer padFrame_lay = Layer.newInstance(this, "Pad-Frame", new EGraphics(EGraphics.SOLID, EGraphics.PATTERNED, 0, 255,0,0, 1.0,false, new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0})); // The layer functions metalLayers[0].setFunction(Layer.Function.METAL1); // Metal-1 metalLayers[1].setFunction(Layer.Function.METAL2); // Metal-2 metalLayers[2].setFunction(Layer.Function.METAL3); // Metal-3 metalLayers[3].setFunction(Layer.Function.METAL4); // Metal-4 metalLayers[4].setFunction(Layer.Function.METAL5); // Metal-5 metalLayers[5].setFunction(Layer.Function.METAL6); // Metal-6 poly1_lay.setFunction(Layer.Function.POLY1); // Polysilicon-1 poly2_lay.setFunction(Layer.Function.POLY2); // Polysilicon-2 activeLayers[P_TYPE].setFunction(Layer.Function.DIFFP); // P-Active activeLayers[N_TYPE].setFunction(Layer.Function.DIFFN); // N-Active selectLayers[P_TYPE].setFunction(Layer.Function.IMPLANTP); // P-Select selectLayers[N_TYPE].setFunction(Layer.Function.IMPLANTN); // N-Select wellLayers[P_TYPE].setFunction(Layer.Function.WELLP); // P-Well wellLayers[N_TYPE].setFunction(Layer.Function.WELLN); // N-Well polyCutLayer.setFunction(Layer.Function.CONTACT1, Layer.Function.CONPOLY); // Poly-Cut activeCut_lay.setFunction(Layer.Function.CONTACT1, Layer.Function.CONDIFF); // Active-Cut via1_lay.setFunction(Layer.Function.CONTACT2, Layer.Function.CONMETAL); // Via-1 via2_lay.setFunction(Layer.Function.CONTACT3, Layer.Function.CONMETAL); // Via-2 via3_lay.setFunction(Layer.Function.CONTACT4, Layer.Function.CONMETAL); // Via-3 via4_lay.setFunction(Layer.Function.CONTACT5, Layer.Function.CONMETAL); // Via-4 via5_lay.setFunction(Layer.Function.CONTACT6, Layer.Function.CONMETAL); // Via-5 passivation_lay.setFunction(Layer.Function.OVERGLASS); // Passivation transistorPoly_lay.setFunction(Layer.Function.GATE); // Transistor-Poly polyCap_lay.setFunction(Layer.Function.CAP); // Poly-Cap pActiveWell_lay.setFunction(Layer.Function.DIFFP); // P-Active-Well silicideBlock_lay.setFunction(Layer.Function.ART); // Silicide-Block thickActive_lay.setFunction(Layer.Function.DIFF, Layer.Function.THICK); // Thick-Active pseudoMetal1_lay.setFunction(Layer.Function.METAL1, Layer.Function.PSEUDO); // Pseudo-Metal-1 pseudoMetal2_lay.setFunction(Layer.Function.METAL2, Layer.Function.PSEUDO); // Pseudo-Metal-2 pseudoMetal3_lay.setFunction(Layer.Function.METAL3, Layer.Function.PSEUDO); // Pseudo-Metal-3 pseudoMetal4_lay.setFunction(Layer.Function.METAL4, Layer.Function.PSEUDO); // Pseudo-Metal-4 pseudoMetal5_lay.setFunction(Layer.Function.METAL5, Layer.Function.PSEUDO); // Pseudo-Metal-5 pseudoMetal6_lay.setFunction(Layer.Function.METAL6, Layer.Function.PSEUDO); // Pseudo-Metal-6 pseudoPoly1_lay.setFunction(Layer.Function.POLY1, Layer.Function.PSEUDO); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFunction(Layer.Function.POLY2, Layer.Function.PSEUDO); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFunction(Layer.Function.DIFFP, Layer.Function.PSEUDO); // Pseudo-P-Active pseudoNActive_lay.setFunction(Layer.Function.DIFFN, Layer.Function.PSEUDO); // Pseudo-N-Active pseudoPSelect_lay.setFunction(Layer.Function.IMPLANTP, Layer.Function.PSEUDO); // Pseudo-P-Select pseudoNSelect_lay.setFunction(Layer.Function.IMPLANTN, Layer.Function.PSEUDO); // Pseudo-N-Select pseudoPWell_lay.setFunction(Layer.Function.WELLP, Layer.Function.PSEUDO); // Pseudo-P-Well pseudoNWell_lay.setFunction(Layer.Function.WELLN, Layer.Function.PSEUDO); // Pseudo-N-Well padFrame_lay.setFunction(Layer.Function.ART); // Pad-Frame // The CIF names metalLayers[0].setFactoryCIFLayer("CMF"); // Metal-1 metalLayers[1].setFactoryCIFLayer("CMS"); // Metal-2 metalLayers[2].setFactoryCIFLayer("CMT"); // Metal-3 metalLayers[3].setFactoryCIFLayer("CMQ"); // Metal-4 metalLayers[4].setFactoryCIFLayer("CMP"); // Metal-5 metalLayers[5].setFactoryCIFLayer("CM6"); // Metal-6 poly1_lay.setFactoryCIFLayer("CPG"); // Polysilicon-1 poly2_lay.setFactoryCIFLayer("CEL"); // Polysilicon-2 activeLayers[P_TYPE].setFactoryCIFLayer("CAA"); // P-Active activeLayers[N_TYPE].setFactoryCIFLayer("CAA"); // N-Active selectLayers[P_TYPE].setFactoryCIFLayer("CSP"); // P-Select selectLayers[N_TYPE].setFactoryCIFLayer("CSN"); // N-Select wellLayers[P_TYPE].setFactoryCIFLayer("CWP"); // P-Well wellLayers[N_TYPE].setFactoryCIFLayer("CWN"); // N-Well polyCutLayer.setFactoryCIFLayer("CCC"); // Poly-Cut activeCut_lay.setFactoryCIFLayer("CCC"); // Active-Cut via1_lay.setFactoryCIFLayer("CVA"); // Via-1 via2_lay.setFactoryCIFLayer("CVS"); // Via-2 via3_lay.setFactoryCIFLayer("CVT"); // Via-3 via4_lay.setFactoryCIFLayer("CVQ"); // Via-4 via5_lay.setFactoryCIFLayer("CV5"); // Via-5 passivation_lay.setFactoryCIFLayer("COG"); // Passivation transistorPoly_lay.setFactoryCIFLayer("CPG"); // Transistor-Poly polyCap_lay.setFactoryCIFLayer("CPC"); // Poly-Cap pActiveWell_lay.setFactoryCIFLayer("CAA"); // P-Active-Well silicideBlock_lay.setFactoryCIFLayer("CSB"); // Silicide-Block thickActive_lay.setFactoryCIFLayer("CTA"); // Thick-Active pseudoMetal1_lay.setFactoryCIFLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryCIFLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryCIFLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryCIFLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryCIFLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryCIFLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryCIFLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryCIFLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactoryCIFLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactoryCIFLayer("CSP"); // Pseudo-P-Select pseudoNSelect_lay.setFactoryCIFLayer("CSN"); // Pseudo-N-Select pseudoPWell_lay.setFactoryCIFLayer("CWP"); // Pseudo-P-Well pseudoNWell_lay.setFactoryCIFLayer("CWN"); // Pseudo-N-Well padFrame_lay.setFactoryCIFLayer("XP"); // Pad-Frame // The GDS names metalLayers[0].setFactoryGDSLayer("49, 80p, 80t", Foundry.MOSIS_FOUNDRY); // Metal-1 Mosis metalLayers[0].setFactoryGDSLayer("16", Foundry.TSMC_FOUNDRY); // Metal-1 TSMC metalLayers[1].setFactoryGDSLayer("51, 82p, 82t", Foundry.MOSIS_FOUNDRY); // Metal-2 metalLayers[1].setFactoryGDSLayer("18", Foundry.TSMC_FOUNDRY); // Metal-2 metalLayers[2].setFactoryGDSLayer("62, 93p, 93t", Foundry.MOSIS_FOUNDRY); // Metal-3 metalLayers[2].setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Metal-3 metalLayers[3].setFactoryGDSLayer("31, 63p, 63t", Foundry.MOSIS_FOUNDRY); // Metal-4 metalLayers[3].setFactoryGDSLayer("31", Foundry.TSMC_FOUNDRY); metalLayers[4].setFactoryGDSLayer("33, 64p, 64t", Foundry.MOSIS_FOUNDRY); // Metal-5 metalLayers[4].setFactoryGDSLayer("33", Foundry.TSMC_FOUNDRY); // Metal-5 metalLayers[5].setFactoryGDSLayer("37, 68p, 68t", Foundry.MOSIS_FOUNDRY); // Metal-6 metalLayers[5].setFactoryGDSLayer("38", Foundry.TSMC_FOUNDRY); // Metal-6 poly1_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Polysilicon-1 poly1_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Polysilicon-1 transistorPoly_lay.setFactoryGDSLayer("46", Foundry.MOSIS_FOUNDRY); // Transistor-Poly transistorPoly_lay.setFactoryGDSLayer("13", Foundry.TSMC_FOUNDRY); // Transistor-Poly poly2_lay.setFactoryGDSLayer("56", Foundry.MOSIS_FOUNDRY); // Polysilicon-2 activeLayers[P_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active activeLayers[P_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active activeLayers[N_TYPE].setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // N-Active activeLayers[N_TYPE].setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // N-Active pActiveWell_lay.setFactoryGDSLayer("43", Foundry.MOSIS_FOUNDRY); // P-Active-Well pActiveWell_lay.setFactoryGDSLayer("3", Foundry.TSMC_FOUNDRY); // P-Active-Well selectLayers[P_TYPE].setFactoryGDSLayer("44", Foundry.MOSIS_FOUNDRY); // P-Select selectLayers[P_TYPE].setFactoryGDSLayer("7", Foundry.TSMC_FOUNDRY); // P-Select selectLayers[N_TYPE].setFactoryGDSLayer("45", Foundry.MOSIS_FOUNDRY); // N-Select selectLayers[N_TYPE].setFactoryGDSLayer("8", Foundry.TSMC_FOUNDRY); // N-Select wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.MOSIS_FOUNDRY); // P-Well wellLayers[P_TYPE].setFactoryGDSLayer("41", Foundry.TSMC_FOUNDRY); // P-Well wellLayers[N_TYPE].setFactoryGDSLayer("42", Foundry.MOSIS_FOUNDRY); // N-Well wellLayers[N_TYPE].setFactoryGDSLayer("2", Foundry.TSMC_FOUNDRY); // N-Well polyCutLayer.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Poly-Cut polyCutLayer.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Poly-Cut activeCut_lay.setFactoryGDSLayer("25", Foundry.MOSIS_FOUNDRY); // Active-Cut activeCut_lay.setFactoryGDSLayer("15", Foundry.TSMC_FOUNDRY); // Active-Cut via1_lay.setFactoryGDSLayer("50", Foundry.MOSIS_FOUNDRY); // Via-1 via1_lay.setFactoryGDSLayer("17", Foundry.TSMC_FOUNDRY); // Via-1 via2_lay.setFactoryGDSLayer("61", Foundry.MOSIS_FOUNDRY); // Via-2 via2_lay.setFactoryGDSLayer("27", Foundry.TSMC_FOUNDRY); // Via-2 via3_lay.setFactoryGDSLayer("30", Foundry.MOSIS_FOUNDRY); // Via-3 via3_lay.setFactoryGDSLayer("29", Foundry.TSMC_FOUNDRY); // Via-3 via4_lay.setFactoryGDSLayer("32", Foundry.MOSIS_FOUNDRY); // Via-4 via4_lay.setFactoryGDSLayer("32", Foundry.TSMC_FOUNDRY); // Via-4 via5_lay.setFactoryGDSLayer("36", Foundry.MOSIS_FOUNDRY); // Via-5 via5_lay.setFactoryGDSLayer("39", Foundry.TSMC_FOUNDRY); // Via-5 passivation_lay.setFactoryGDSLayer("52", Foundry.MOSIS_FOUNDRY); // Passivation passivation_lay.setFactoryGDSLayer("19", Foundry.TSMC_FOUNDRY); // Passivation polyCap_lay.setFactoryGDSLayer("28", Foundry.MOSIS_FOUNDRY); // Poly-Cap polyCap_lay.setFactoryGDSLayer("28", Foundry.TSMC_FOUNDRY); // Poly-Cap silicideBlock_lay.setFactoryGDSLayer("29", Foundry.MOSIS_FOUNDRY); // Silicide-Block silicideBlock_lay.setFactoryGDSLayer("34", Foundry.TSMC_FOUNDRY); // Silicide-Block thickActive_lay.setFactoryGDSLayer("60", Foundry.MOSIS_FOUNDRY); // Thick-Active thickActive_lay.setFactoryGDSLayer("4", Foundry.TSMC_FOUNDRY); // Thick-Active pseudoMetal1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Active pseudoNActive_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Active pseudoPSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Select pseudoNSelect_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Select pseudoPWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-P-Well pseudoNWell_lay.setFactoryGDSLayer("", Foundry.MOSIS_FOUNDRY); // Pseudo-N-Well padFrame_lay.setFactoryGDSLayer("26", Foundry.MOSIS_FOUNDRY); // Pad-Frame padFrame_lay.setFactoryGDSLayer("26", Foundry.TSMC_FOUNDRY); // Pad-Frame // The Skill names metalLayers[0].setFactorySkillLayer("metal1"); // Metal-1 metalLayers[1].setFactorySkillLayer("metal2"); // Metal-2 metalLayers[2].setFactorySkillLayer("metal3"); // Metal-3 metalLayers[3].setFactorySkillLayer("metal4"); // Metal-4 metalLayers[4].setFactorySkillLayer("metal5"); // Metal-5 metalLayers[5].setFactorySkillLayer("metal6"); // Metal-6 poly1_lay.setFactorySkillLayer("poly"); // Polysilicon-1 poly2_lay.setFactorySkillLayer(""); // Polysilicon-2 activeLayers[P_TYPE].setFactorySkillLayer("aa"); // P-Active activeLayers[N_TYPE].setFactorySkillLayer("aa"); // N-Active selectLayers[P_TYPE].setFactorySkillLayer("pplus"); // P-Select selectLayers[N_TYPE].setFactorySkillLayer("nplus"); // N-Select wellLayers[P_TYPE].setFactorySkillLayer("pwell"); // P-Well wellLayers[N_TYPE].setFactorySkillLayer("nwell"); // N-Well polyCutLayer.setFactorySkillLayer("pcont"); // Poly-Cut activeCut_lay.setFactorySkillLayer("acont"); // Active-Cut via1_lay.setFactorySkillLayer("via"); // Via-1 via2_lay.setFactorySkillLayer("via2"); // Via-2 via3_lay.setFactorySkillLayer("via3"); // Via-3 via4_lay.setFactorySkillLayer("via4"); // Via-4 via5_lay.setFactorySkillLayer("via5"); // Via-5 passivation_lay.setFactorySkillLayer("glasscut"); // Passivation transistorPoly_lay.setFactorySkillLayer("poly"); // Transistor-Poly polyCap_lay.setFactorySkillLayer(""); // Poly-Cap pActiveWell_lay.setFactorySkillLayer("aa"); // P-Active-Well silicideBlock_lay.setFactorySkillLayer(""); // Silicide-Block thickActive_lay.setFactorySkillLayer(""); // Thick-Active pseudoMetal1_lay.setFactorySkillLayer(""); // Pseudo-Metal-1 pseudoMetal2_lay.setFactorySkillLayer(""); // Pseudo-Metal-2 pseudoMetal3_lay.setFactorySkillLayer(""); // Pseudo-Metal-3 pseudoMetal4_lay.setFactorySkillLayer(""); // Pseudo-Metal-4 pseudoMetal5_lay.setFactorySkillLayer(""); // Pseudo-Metal-5 pseudoMetal6_lay.setFactorySkillLayer(""); // Pseudo-Metal-6 pseudoPoly1_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactorySkillLayer(""); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactorySkillLayer(""); // Pseudo-P-Active pseudoNActive_lay.setFactorySkillLayer(""); // Pseudo-N-Active pseudoPSelect_lay.setFactorySkillLayer("pplus"); // Pseudo-P-Select pseudoNSelect_lay.setFactorySkillLayer("nplus"); // Pseudo-N-Select pseudoPWell_lay.setFactorySkillLayer("pwell"); // Pseudo-P-Well pseudoNWell_lay.setFactorySkillLayer("nwell"); // Pseudo-N-Well padFrame_lay.setFactorySkillLayer(""); // Pad-Frame // The layer distance // Data base on 18nm technology with 200nm as grid unit. double BULK_LAYER = 10; double DIFF_LAYER = 1; // dummy distance for now 0.2/0.2 double ILD_LAYER = 3.5; // 0.7/0.2 convertLength() double IMD_LAYER = 5.65; // 1.13um/0.2 double METAL_LAYER = 2.65; // 0.53um/0.2 activeLayers[P_TYPE].setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active 0.17um/0.2 = activeLayers[N_TYPE].setFactory3DInfo(0.8, BULK_LAYER + 2*DIFF_LAYER); // N-Active 0.16um/0.2 selectLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // P-Select selectLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER + DIFF_LAYER); // N-Select wellLayers[P_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // P-Well wellLayers[N_TYPE].setFactory3DInfo(DIFF_LAYER, BULK_LAYER); // N-Well pActiveWell_lay.setFactory3DInfo(0.85, BULK_LAYER + 2*DIFF_LAYER); // P-Active-Well thickActive_lay.setFactory3DInfo(0.5, BULK_LAYER + 0.5); // Thick Active (between select and well) metalLayers[0].setFactory3DInfo(METAL_LAYER, ILD_LAYER + activeLayers[P_TYPE].getDepth()); // Metal-1 0.53um/0.2 metalLayers[1].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[0].getDistance()); // Metal-2 via1_lay.setFactory3DInfo(metalLayers[1].getDistance()-metalLayers[0].getDepth(), metalLayers[0].getDepth()); // Via-1 metalLayers[2].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[1].getDistance()); // Metal-3 via2_lay.setFactory3DInfo(metalLayers[2].getDistance()-metalLayers[1].getDepth(), metalLayers[1].getDepth()); // Via-2 metalLayers[3].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[2].getDistance()); // Metal-4 via3_lay.setFactory3DInfo(metalLayers[3].getDistance()-metalLayers[2].getDepth(), metalLayers[2].getDepth()); // Via-3 metalLayers[4].setFactory3DInfo(METAL_LAYER, IMD_LAYER + metalLayers[3].getDistance()); // Metal-5 via4_lay.setFactory3DInfo(metalLayers[4].getDistance()-metalLayers[3].getDepth(), metalLayers[3].getDepth()); // Via-4 metalLayers[5].setFactory3DInfo(4.95, IMD_LAYER + metalLayers[4].getDistance()); // Metal-6 0.99um/0.2 via5_lay.setFactory3DInfo(metalLayers[5].getDistance()-metalLayers[4].getDepth(), metalLayers[4].getDepth()); // Via-5 double PASS_LAYER = 5; // 1um/0.2 double PO_LAYER = 1; // 0.2/0.2 double FOX_LAYER = 1.75; // 0.35/0.2 double TOX_LAYER = 0; // Very narrow thin oxide in gate /* for displaying pins */ pseudoMetal1_lay.setFactory3DInfo(0, metalLayers[0].getDistance()); // Pseudo-Metal-1 pseudoMetal2_lay.setFactory3DInfo(0, metalLayers[1].getDistance()); // Pseudo-Metal-2 pseudoMetal3_lay.setFactory3DInfo(0, metalLayers[2].getDistance()); // Pseudo-Metal-3 pseudoMetal4_lay.setFactory3DInfo(0, metalLayers[3].getDistance()); // Pseudo-Metal-4 pseudoMetal5_lay.setFactory3DInfo(0, metalLayers[4].getDistance()); // Pseudo-Metal-5 pseudoMetal6_lay.setFactory3DInfo(0, metalLayers[5].getDistance()); // Pseudo-Metal-6 // Poly layers poly1_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Polysilicon-1 transistorPoly_lay.setFactory3DInfo(PO_LAYER, TOX_LAYER + activeLayers[P_TYPE].getDepth()); // Transistor-Poly poly2_lay.setFactory3DInfo(PO_LAYER, transistorPoly_lay.getDepth()); // Polysilicon-2 // on top of transistor layer? polyCap_lay.setFactory3DInfo(PO_LAYER, FOX_LAYER + activeLayers[P_TYPE].getDepth()); // Poly-Cap @TODO GVG Ask polyCap polyCutLayer.setFactory3DInfo(metalLayers[0].getDistance()-poly1_lay.getDepth(), poly1_lay.getDepth()); // Poly-Cut between poly and metal1 activeCut_lay.setFactory3DInfo(metalLayers[0].getDistance()-activeLayers[N_TYPE].getDepth(), activeLayers[N_TYPE].getDepth()); // Active-Cut betweent active and metal1 // Other layers passivation_lay.setFactory3DInfo(PASS_LAYER, metalLayers[5].getDepth()); // Passivation silicideBlock_lay.setFactory3DInfo(0, BULK_LAYER); // Silicide-Block padFrame_lay.setFactory3DInfo(0, passivation_lay.getDepth()); // Pad-Frame pseudoPoly1_lay.setFactory3DInfo(0, poly1_lay.getDistance()); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactory3DInfo(0, poly2_lay.getDistance()); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactory3DInfo(0, activeLayers[P_TYPE].getDistance()); // Pseudo-P-Active pseudoNActive_lay.setFactory3DInfo(0, activeLayers[N_TYPE].getDistance()); // Pseudo-N-Active pseudoPSelect_lay.setFactory3DInfo(0, selectLayers[P_TYPE].getDistance()); // Pseudo-P-Select pseudoNSelect_lay.setFactory3DInfo(0, selectLayers[N_TYPE].getDistance()); // Pseudo-N-Select pseudoPWell_lay.setFactory3DInfo(0, wellLayers[P_TYPE].getDistance()); // Pseudo-P-Well pseudoNWell_lay.setFactory3DInfo(0, wellLayers[N_TYPE].getDistance()); // Pseudo-N-Well // The Spice parasitics metalLayers[0].setFactoryParasitics(0.078, 0.1209, 0.1104); // Metal-1 metalLayers[1].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-2 metalLayers[2].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-3 metalLayers[3].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-4 metalLayers[4].setFactoryParasitics(0.078, 0.0843, 0.0974); // Metal-5 metalLayers[5].setFactoryParasitics(0.036, 0.0423, 0.1273); // Metal-6 poly1_lay.setFactoryParasitics(6.2, 0.1467, 0.0608); // Polysilicon-1 poly2_lay.setFactoryParasitics(50.0, 1.0, 0); // Polysilicon-2 activeLayers[P_TYPE].setFactoryParasitics(2.5, 0.9, 0); // P-Active activeLayers[N_TYPE].setFactoryParasitics(3.0, 0.9, 0); // N-Active selectLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Select selectLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Select wellLayers[P_TYPE].setFactoryParasitics(0, 0, 0); // P-Well wellLayers[N_TYPE].setFactoryParasitics(0, 0, 0); // N-Well polyCutLayer.setFactoryParasitics(2.2, 0, 0); // Poly-Cut activeCut_lay.setFactoryParasitics(2.5, 0, 0); // Active-Cut via1_lay.setFactoryParasitics(1.0, 0, 0); // Via-1 via2_lay.setFactoryParasitics(0.9, 0, 0); // Via-2 via3_lay.setFactoryParasitics(0.8, 0, 0); // Via-3 via4_lay.setFactoryParasitics(0.8, 0, 0); // Via-4 via5_lay.setFactoryParasitics(0.8, 0, 0); // Via-5 passivation_lay.setFactoryParasitics(0, 0, 0); // Passivation transistorPoly_lay.setFactoryParasitics(2.5, 0.09, 0); // Transistor-Poly polyCap_lay.setFactoryParasitics(0, 0, 0); // Poly-Cap pActiveWell_lay.setFactoryParasitics(0, 0, 0); // P-Active-Well silicideBlock_lay.setFactoryParasitics(0, 0, 0); // Silicide-Block thickActive_lay.setFactoryParasitics(0, 0, 0); // Thick-Active pseudoMetal1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-1 pseudoMetal2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-2 pseudoMetal3_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-3 pseudoMetal4_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-4 pseudoMetal5_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-5 pseudoMetal6_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Metal-6 pseudoPoly1_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-1 pseudoPoly2_lay.setFactoryParasitics(0, 0, 0); // Pseudo-Polysilicon-2 pseudoPActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Active pseudoNActive_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Active pseudoPSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Select pseudoNSelect_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Select pseudoPWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-P-Well pseudoNWell_lay.setFactoryParasitics(0, 0, 0); // Pseudo-N-Well padFrame_lay.setFactoryParasitics(0, 0, 0); // Pad-Frame setFactoryParasitics(4, 0.1); String [] headerLevel1 = { "*CMOS/BULK-NWELL (PRELIMINARY PARAMETERS)", ".OPTIONS NOMOD DEFL=3UM DEFW=3UM DEFAD=70P DEFAS=70P LIMPTS=1000", "+ITL5=0 RELTOL=0.01 ABSTOL=500PA VNTOL=500UV LVLTIM=2", "+LVLCOD=1", ".MODEL N NMOS LEVEL=1", "+KP=60E-6 VTO=0.7 GAMMA=0.3 LAMBDA=0.05 PHI=0.6", "+LD=0.4E-6 TOX=40E-9 CGSO=2.0E-10 CGDO=2.0E-10 CJ=.2MF/M^2", ".MODEL P PMOS LEVEL=1", "+KP=20E-6 VTO=0.7 GAMMA=0.4 LAMBDA=0.05 PHI=0.6", "+LD=0.6E-6 TOX=40E-9 CGSO=3.0E-10 CGDO=3.0E-10 CJ=.2MF/M^2", ".MODEL DIFFCAP D CJO=.2MF/M^2" }; setSpiceHeaderLevel1(headerLevel1); String [] headerLevel2 = { "* MOSIS 3u CMOS PARAMS", ".OPTIONS NOMOD DEFL=2UM DEFW=6UM DEFAD=100P DEFAS=100P", "+LIMPTS=1000 ITL5=0 ABSTOL=500PA VNTOL=500UV", "* Note that ITL5=0 sets ITL5 to infinity", ".MODEL N NMOS LEVEL=2 LD=0.3943U TOX=502E-10", "+NSUB=1.22416E+16 VTO=0.756 KP=4.224E-05 GAMMA=0.9241", "+PHI=0.6 UO=623.661 UEXP=8.328627E-02 UCRIT=54015.0", "+DELTA=5.218409E-03 VMAX=50072.2 XJ=0.4U LAMBDA=2.975321E-02", "+NFS=4.909947E+12 NEFF=1.001E-02 NSS=0.0 TPG=1.0", "+RSH=20.37 CGDO=3.1E-10 CGSO=3.1E-10", "+CJ=3.205E-04 MJ=0.4579 CJSW=4.62E-10 MJSW=0.2955 PB=0.7", ".MODEL P PMOS LEVEL=2 LD=0.2875U TOX=502E-10", "+NSUB=1.715148E+15 VTO=-0.7045 KP=1.686E-05 GAMMA=0.3459", "+PHI=0.6 UO=248.933 UEXP=1.02652 UCRIT=182055.0", "+DELTA=1.0E-06 VMAX=100000.0 XJ=0.4U LAMBDA=1.25919E-02", "+NFS=1.0E+12 NEFF=1.001E-02 NSS=0.0 TPG=-1.0", "+RSH=79.10 CGDO=2.89E-10 CGSO=2.89E-10", "+CJ=1.319E-04 MJ=0.4125 CJSW=3.421E-10 MJSW=0.198 PB=0.66", ".TEMP 25.0" }; setSpiceHeaderLevel2(headerLevel2); //**************************************** ARCS **************************************** /** metal 1 arc */ metalArcs[0] = ArcProto.newInstance(this, "Metal-1", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[0], 0, Poly.Type.FILLED) }); metalArcs[0].setFunction(ArcProto.Function.METAL1); metalArcs[0].setFactoryFixedAngle(true); metalArcs[0].setWipable(); metalArcs[0].setFactoryAngleIncrement(90); /** metal 2 arc */ metalArcs[1] = ArcProto.newInstance(this, "Metal-2", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[1], 0, Poly.Type.FILLED) }); metalArcs[1].setFunction(ArcProto.Function.METAL2); metalArcs[1].setFactoryFixedAngle(true); metalArcs[1].setWipable(); metalArcs[1].setFactoryAngleIncrement(90); /** metal 3 arc */ metalArcs[2] = ArcProto.newInstance(this, "Metal-3", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[2], 0, Poly.Type.FILLED) }); metalArcs[2].setFunction(ArcProto.Function.METAL3); metalArcs[2].setFactoryFixedAngle(true); metalArcs[2].setWipable(); metalArcs[2].setFactoryAngleIncrement(90); /** metal 4 arc */ metalArcs[3] = ArcProto.newInstance(this, "Metal-4", 6.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[3], 0, Poly.Type.FILLED) }); metalArcs[3].setFunction(ArcProto.Function.METAL4); metalArcs[3].setFactoryFixedAngle(true); metalArcs[3].setWipable(); metalArcs[3].setFactoryAngleIncrement(90); /** metal 5 arc */ metalArcs[4] = ArcProto.newInstance(this, "Metal-5", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[4], 0, Poly.Type.FILLED) }); metalArcs[4].setFunction(ArcProto.Function.METAL5); metalArcs[4].setFactoryFixedAngle(true); metalArcs[4].setWipable(); metalArcs[4].setFactoryAngleIncrement(90); /** metal 6 arc */ metalArcs[5] = ArcProto.newInstance(this, "Metal-6", 4.0, new Technology.ArcLayer [] { new Technology.ArcLayer(metalLayers[5], 0, Poly.Type.FILLED) }); metalArcs[5].setFunction(ArcProto.Function.METAL6); metalArcs[5].setFactoryFixedAngle(true); metalArcs[5].setWipable(); metalArcs[5].setFactoryAngleIncrement(90); /** polysilicon 1 arc */ poly1_arc = ArcProto.newInstance(this, "Polysilicon-1", 2.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly1_lay, 0, Poly.Type.FILLED) }); poly1_arc.setFunction(ArcProto.Function.POLY1); poly1_arc.setFactoryFixedAngle(true); poly1_arc.setWipable(); poly1_arc.setFactoryAngleIncrement(90); /** polysilicon 2 arc */ poly2_arc = ArcProto.newInstance(this, "Polysilicon-2", 7.0, new Technology.ArcLayer [] { new Technology.ArcLayer(poly2_lay, 0, Poly.Type.FILLED) }); poly2_arc.setFunction(ArcProto.Function.POLY2); poly2_arc.setFactoryFixedAngle(true); poly2_arc.setWipable(); poly2_arc.setFactoryAngleIncrement(90); poly2_arc.setNotUsed(); /** P-active arc */ activeArcs[P_TYPE] = ArcProto.newInstance(this, "P-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[P_TYPE], 8, Poly.Type.FILLED) }); activeArcs[P_TYPE].setFunction(ArcProto.Function.DIFFP); activeArcs[P_TYPE].setFactoryFixedAngle(true); activeArcs[P_TYPE].setWipable(); activeArcs[P_TYPE].setFactoryAngleIncrement(90); activeArcs[P_TYPE].setWidthOffset(12.0); /** N-active arc */ activeArcs[N_TYPE] = ArcProto.newInstance(this, "N-Active", 15.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[N_TYPE], 12, Poly.Type.FILLED), new Technology.ArcLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(selectLayers[N_TYPE], 8, Poly.Type.FILLED) }); activeArcs[N_TYPE].setFunction(ArcProto.Function.DIFFN); activeArcs[N_TYPE].setFactoryFixedAngle(true); activeArcs[N_TYPE].setWipable(); activeArcs[N_TYPE].setFactoryAngleIncrement(90); activeArcs[N_TYPE].setWidthOffset(12.0); /** General active arc */ active_arc = ArcProto.newInstance(this, "Active", 3.0, new Technology.ArcLayer [] { new Technology.ArcLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED), new Technology.ArcLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED) }); active_arc.setFunction(ArcProto.Function.DIFF); active_arc.setFactoryFixedAngle(true); active_arc.setWipable(); active_arc.setFactoryAngleIncrement(90); active_arc.setNotUsed(); //**************************************** NODES **************************************** /** metal-1-pin */ metalPinNodes[0] = PrimitiveNode.newInstance("Metal-1-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[0], new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[0].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[0].setArcsWipe(); metalPinNodes[0].setArcsShrink(); /** metal-2-pin */ metalPinNodes[1] = PrimitiveNode.newInstance("Metal-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[1], new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[1].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[1].setArcsWipe(); metalPinNodes[1].setArcsShrink(); /** metal-3-pin */ metalPinNodes[2] = PrimitiveNode.newInstance("Metal-3-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal3_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[2], new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[2].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[2].setArcsWipe(); metalPinNodes[2].setArcsShrink(); /** metal-4-pin */ metalPinNodes[3] = PrimitiveNode.newInstance("Metal-4-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal4_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[3], new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[3].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[3].setArcsWipe(); metalPinNodes[3].setArcsShrink(); /** metal-5-pin */ metalPinNodes[4] = PrimitiveNode.newInstance("Metal-5-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal5_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[4], new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[4].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[4].setArcsWipe(); metalPinNodes[4].setArcsShrink(); metalPinNodes[4].setNotUsed(); /** metal-6-pin */ metalPinNodes[5] = PrimitiveNode.newInstance("Metal-6-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoMetal6_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metalPinNodes[5].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalPinNodes[5], new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalPinNodes[5].setFunction(PrimitiveNode.Function.PIN); metalPinNodes[5].setArcsWipe(); metalPinNodes[5].setArcsShrink(); metalPinNodes[5].setNotUsed(); /** polysilicon-1-pin */ poly1Pin_node = PrimitiveNode.newInstance("Polysilicon-1-Pin", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly1_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Pin_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Pin_node.setFunction(PrimitiveNode.Function.PIN); poly1Pin_node.setArcsWipe(); poly1Pin_node.setArcsShrink(); /** polysilicon-2-pin */ poly2Pin_node = PrimitiveNode.newInstance("Polysilicon-2-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPoly2_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Pin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Pin_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Pin_node.setFunction(PrimitiveNode.Function.PIN); poly2Pin_node.setArcsWipe(); poly2Pin_node.setArcsShrink(); poly2Pin_node.setNotUsed(); /** P-active-pin */ activePinNodes[P_TYPE] = PrimitiveNode.newInstance("P-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoNWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoPSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE]}, "p-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[P_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[P_TYPE].setArcsWipe(); activePinNodes[P_TYPE].setArcsShrink(); /** N-active-pin */ activePinNodes[N_TYPE] = PrimitiveNode.newInstance("N-Active-Pin", this, 15.0, 15.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(pseudoPWell_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNSelect_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); activePinNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePinNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE]}, "n-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7.5)) }); activePinNodes[N_TYPE].setFunction(PrimitiveNode.Function.PIN); activePinNodes[N_TYPE].setArcsWipe(); activePinNodes[N_TYPE].setArcsShrink(); /** General active-pin */ activePin_node = PrimitiveNode.newInstance("Active-Pin", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pseudoPActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(pseudoNActive_lay, 0, Poly.Type.CROSSED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activePin_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activePin_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); activePin_node.setFunction(PrimitiveNode.Function.PIN); activePin_node.setArcsWipe(); activePin_node.setArcsShrink(); activePin_node.setNotUsed(); /** metal-1-P-active-contact */ metalActiveContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX,Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "metal-1-p-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[P_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-N-active-contact */ metalActiveContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Active-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalActiveContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalActiveContactNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "metal-1-n-act", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalActiveContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.CONTACT); metalActiveContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalActiveContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalActiveContactNodes[N_TYPE].setMinSize(17, 17, "6.2, 7.3"); /** metal-1-polysilicon-1-contact */ metal1Poly1Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-Con", this, 5.0, 5.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metal1Poly1Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly1Contact_node, new ArcProto[] {poly1_arc, metalArcs[0]}, "metal-1-polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2), EdgeV.fromBottom(2), EdgeH.fromRight(2), EdgeV.fromTop(2)) }); metal1Poly1Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly1Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly1Contact_node.setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metal1Poly1Contact_node.setMinSize(5, 5, "5.2, 7.3"); /** metal-1-polysilicon-2-contact */ metal1Poly2Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-2-Con", this, 10.0, 10.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)) }); metal1Poly2Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly2Contact_node, new ArcProto[] {poly2_arc, metalArcs[0]}, "metal-1-polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4.5), EdgeV.fromBottom(4.5), EdgeH.fromRight(4.5), EdgeV.fromTop(4.5)) }); metal1Poly2Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly2Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly2Contact_node.setSpecialValues(new double [] {2, 2, 4, 4, 3, 3}); metal1Poly2Contact_node.setNotUsed(); metal1Poly2Contact_node.setMinSize(10, 10, "?"); /** metal-1-polysilicon-1-2-contact */ metal1Poly12Contact_node = PrimitiveNode.newInstance("Metal-1-Polysilicon-1-2-Con", this, 15.0, 15.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5.5)), new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(5)), new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)) }); metal1Poly12Contact_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Poly12Contact_node, new ArcProto[] {poly1_arc, poly2_arc, metalArcs[0]}, "metal-1-polysilicon-1-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7), EdgeV.fromBottom(7), EdgeH.fromRight(7), EdgeV.fromTop(7)) }); metal1Poly12Contact_node.setFunction(PrimitiveNode.Function.CONTACT); metal1Poly12Contact_node.setSpecialType(PrimitiveNode.MULTICUT); metal1Poly12Contact_node.setSpecialValues(new double [] {2, 2, 6.5, 6.5, 3, 3}); metal1Poly12Contact_node.setNotUsed(); metal1Poly12Contact_node.setMinSize(15, 15, "?"); /** P-Transistor */ /** N-Transistor */ String[] stdNames = {"p", "n"}; for (int i = 0; i < 2; i++) { transistorPolyLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyLLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyRLayers[i] = new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorPolyCLayers[i] = new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(10))}, 1, 1, 2, 2); transistorActiveLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveTLayers[i] = new Technology.NodeLayer(activeLayers[i], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(10)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(7))}, 4, 4, 0, 0); transistorActiveBLayers[i] = new Technology.NodeLayer(activeLayers[i], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(7)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(10))}, 4, 4, 0, 0); transistorWellLayers[i] = new Technology.NodeLayer(wellLayers[(i+1)%transistorNodes.length], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); transistorSelectLayers[i] = new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(4), EdgeV.fromBottom(5)), new Technology.TechPoint(EdgeH.fromRight(4), EdgeV.fromTop(5))}, 6, 6, 2, 2); transistorNodes[i] = PrimitiveNode.newInstance(stdNames[i].toUpperCase()+"-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {transistorActiveLayers[i], transistorPolyLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {transistorActiveTLayers[i], transistorActiveBLayers[i], transistorPolyCLayers[i], transistorPolyLLayers[i], transistorPolyRLayers[i], transistorWellLayers[i], transistorSelectLayers[i]}); transistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {poly1_arc}, stdNames[i]+"-trans-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, transistorNodes[i], new ArcProto[] {activeArcs[i]}, stdNames[i]+"-trans-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); transistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); transistorNodes[i].setHoldsOutline(); transistorNodes[i].setCanShrink(); transistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); transistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); transistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); } /** Thick oxide transistors */ String[] thickNames = {"Thick-P", "Thick-N"}; Technology.NodeLayer[] thickActiveLayers = new Technology.NodeLayer[] {transistorActiveLayers[P_TYPE], transistorActiveLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLayers = new Technology.NodeLayer[] {transistorPolyLayers[P_TYPE], transistorPolyLayers[N_TYPE]}; Technology.NodeLayer[] thickWellLayers = new Technology.NodeLayer[] {transistorWellLayers[P_TYPE], transistorWellLayers[N_TYPE]}; Technology.NodeLayer[] thickSelectLayers = new Technology.NodeLayer[] {transistorSelectLayers[P_TYPE], transistorSelectLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveTLayers = new Technology.NodeLayer[] {transistorActiveTLayers[P_TYPE], transistorActiveTLayers[N_TYPE]}; Technology.NodeLayer[] thickActiveBLayers = new Technology.NodeLayer[] {transistorActiveBLayers[P_TYPE], transistorActiveBLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyCLayers = new Technology.NodeLayer[] {transistorPolyCLayers[P_TYPE], transistorPolyCLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyLLayers = new Technology.NodeLayer[] {transistorPolyLLayers[P_TYPE], transistorPolyLLayers[N_TYPE]}; Technology.NodeLayer[] thickPolyRLayers = new Technology.NodeLayer[] {transistorPolyRLayers[P_TYPE], transistorPolyRLayers[N_TYPE]}; Technology.NodeLayer[] thickLayers = new Technology.NodeLayer[2]; for (int i = 0; i < thickLayers.length; i++) { thickLayers[i] = new Technology.NodeLayer(thickActive_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(1)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(1))}, 10, 10, 6, 6); } for (int i = 0; i < thickTransistorNodes.length; i++) { thickTransistorNodes[i] = PrimitiveNode.newInstance(thickNames[i] + "-Transistor", this, 15.0, 22.0, new SizeOffset(6, 6, 10, 10), new Technology.NodeLayer [] {thickActiveLayers[i], thickPolyLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].setElectricalLayers(new Technology.NodeLayer [] {thickActiveTLayers[i], thickActiveBLayers[i], thickPolyCLayers[i], thickPolyLLayers[i], thickPolyRLayers[i], thickWellLayers[i], thickSelectLayers[i], thickLayers[i]}); thickTransistorNodes[i].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(4), EdgeV.fromBottom(11), EdgeH.fromLeft(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5), EdgeH.fromRight(7.5), EdgeV.fromTop(7)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {poly1_arc}, "poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromRight(4), EdgeV.fromBottom(11), EdgeH.fromRight(4), EdgeV.fromTop(11)), PrimitivePort.newInstance(this, thickTransistorNodes[i], new ArcProto[] {activeArcs[i]}, "diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(7.5), EdgeV.fromBottom(7), EdgeH.fromRight(7.5), EdgeV.fromBottom(7.5)) }); thickTransistorNodes[i].setFunction((i==P_TYPE) ? PrimitiveNode.Function.TRAPMOS : PrimitiveNode.Function.TRANMOS); thickTransistorNodes[i].setHoldsOutline(); thickTransistorNodes[i].setCanShrink(); thickTransistorNodes[i].setSpecialType(PrimitiveNode.SERPTRANS); thickTransistorNodes[i].setSpecialValues(new double [] {7, 1.5, 2.5, 2, 1, 2}); thickTransistorNodes[i].setMinSize(15, 22, "2.1, 3.1"); thickTransistorNodes[i].setSpecialNode(); // For display purposes } /** Scalable-P-Transistor */ scalableTransistorNodes[P_TYPE] = PrimitiveNode.newInstance("P-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {poly1_arc}, "p-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[P_TYPE], new ArcProto[] {activeArcs[P_TYPE], metalArcs[0]}, "p-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[P_TYPE].setFunction(PrimitiveNode.Function.TRAPMOS); scalableTransistorNodes[P_TYPE].setCanShrink(); scalableTransistorNodes[P_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** Scalable-N-Transistor */ scalableTransistorNodes[N_TYPE] = PrimitiveNode.newInstance("N-Transistor-Scalable", this, 17.0, 26.0, new SizeOffset(7, 7, 12, 12), new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromTop(6)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromTop(11))}), new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromTop(6.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromTop(10.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6), EdgeV.fromBottom(11)), new Technology.TechPoint(EdgeH.fromRight(6), EdgeV.fromBottom(6))}), new Technology.NodeLayer(metalLayers[0], 3, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(6.5), EdgeV.fromBottom(10.5)), new Technology.TechPoint(EdgeH.fromRight(6.5), EdgeV.fromBottom(6.5))}), new Technology.NodeLayer(activeLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7), EdgeV.fromBottom(9)), new Technology.TechPoint(EdgeH.fromRight(7), EdgeV.fromTop(9))}), new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(5), EdgeV.fromBottom(12)), new Technology.TechPoint(EdgeH.fromRight(5), EdgeV.fromTop(12))}), new Technology.NodeLayer(wellLayers[P_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromBottom(9.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromBottom(7.5))}), new Technology.NodeLayer(activeCut_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(7.5), EdgeV.fromTop(7.5)), new Technology.TechPoint(EdgeH.fromLeft(9.5), EdgeV.fromTop(9.5))}) }); scalableTransistorNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-left", 180,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(-3.5), EdgeV.makeCenter(), EdgeH.fromCenter(-3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-top", 90,90, 1, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(4.5), EdgeH.makeCenter(), EdgeV.fromCenter(4.5)), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {poly1_arc}, "n-trans-sca-poly-right", 0,90, 0, PortCharacteristic.UNKNOWN, EdgeH.fromCenter(3.5), EdgeV.makeCenter(), EdgeH.fromCenter(3.5), EdgeV.makeCenter()), PrimitivePort.newInstance(this, scalableTransistorNodes[N_TYPE], new ArcProto[] {activeArcs[N_TYPE], metalArcs[0]}, "n-trans-sca-diff-bottom", 270,90, 2, PortCharacteristic.UNKNOWN, EdgeH.makeCenter(), EdgeV.fromCenter(-4.5), EdgeH.makeCenter(), EdgeV.fromCenter(-4.5)) }); scalableTransistorNodes[N_TYPE].setFunction(PrimitiveNode.Function.TRANMOS); scalableTransistorNodes[N_TYPE].setCanShrink(); scalableTransistorNodes[N_TYPE].setMinSize(17, 26, "2.1, 3.1"); /** metal-1-metal-2-contact */ metalContactNodes[0] = PrimitiveNode.newInstance("Metal-1-Metal-2-Con", this, 5.0, 5.0, new SizeOffset(0.5, 0.5, 0.5, 0.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(0.5)), new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)) }); metalContactNodes[0].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[0], new ArcProto[] {metalArcs[0], metalArcs[1]}, "metal-1-metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metalContactNodes[0].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[0].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[0].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[0].setMinSize(5, 5, "8.3, 9.3"); /** metal-2-metal-3-contact */ metalContactNodes[1] = PrimitiveNode.newInstance("Metal-2-Metal-3-Con", this, 6.0, 6.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[1].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[1], new ArcProto[] {metalArcs[1], metalArcs[2]}, "metal-2-metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[1].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[1].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[1].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[1].setMinSize(6, 6, "14.3, 15.3"); /** metal-3-metal-4-contact */ metalContactNodes[2] = PrimitiveNode.newInstance("Metal-3-Metal-4-Con", this, 6.0, 6.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2)) }); metalContactNodes[2].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[2], new ArcProto[] {metalArcs[2], metalArcs[3]}, "metal-3-metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[2].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[2].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[2].setSpecialValues(new double [] {2, 2, 2, 2, 3, 3}); metalContactNodes[2].setMinSize(6, 6, "21.3, 22.3"); /** metal-4-metal-5-contact */ metalContactNodes[3] = PrimitiveNode.newInstance("Metal-4-Metal-5-Con", this, 7.0, 7.0, new SizeOffset(1.5, 1.5, 1.5, 1.5), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1.5)), new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(2.5)) }); metalContactNodes[3].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[3], new ArcProto[] {metalArcs[3], metalArcs[4]}, "metal-4-metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[3].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[3].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[3].setSpecialValues(new double [] {2, 2, 1, 1, 3, 3}); metalContactNodes[3].setNotUsed(); metalContactNodes[3].setMinSize(7, 7, "25.3, 26.3"); /** metal-5-metal-6-contact */ metalContactNodes[4] = PrimitiveNode.newInstance("Metal-5-Metal-6-Con", this, 8.0, 8.0, new SizeOffset(1, 1, 1, 1), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(1)), new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(3)) }); metalContactNodes[4].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalContactNodes[4], new ArcProto[] {metalArcs[4], metalArcs[5]}, "metal-5-metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(2.5), EdgeV.fromBottom(2.5), EdgeH.fromRight(2.5), EdgeV.fromTop(2.5)) }); metalContactNodes[4].setFunction(PrimitiveNode.Function.CONTACT); metalContactNodes[4].setSpecialType(PrimitiveNode.MULTICUT); metalContactNodes[4].setSpecialValues(new double [] {3, 3, 2, 2, 4, 4}); metalContactNodes[4].setNotUsed(); metalContactNodes[4].setMinSize(8, 8, "29.3, 30.3"); /** Metal-1-P-Well Contact */ metalWellContactNodes[P_TYPE] = PrimitiveNode.newInstance("Metal-1-P-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[P_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[P_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[P_TYPE].setFunction(PrimitiveNode.Function.WELL); metalWellContactNodes[P_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[P_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[P_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /** Metal-1-N-Well Contact */ metalWellContactNodes[N_TYPE] = PrimitiveNode.newInstance("Metal-1-N-Well-Con", this, 17.0, 17.0, new SizeOffset(6, 6, 6, 6), new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6.5)), new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(6)), new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()), new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(4)), new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeIndented(7.5)) }); metalWellContactNodes[N_TYPE].addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metalWellContactNodes[N_TYPE], new ArcProto[] {metalArcs[0], active_arc}, "metal-1-substrate", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(8), EdgeV.fromBottom(8), EdgeH.fromRight(8), EdgeV.fromTop(8)) }); metalWellContactNodes[N_TYPE].setFunction(PrimitiveNode.Function.SUBSTRATE); metalWellContactNodes[N_TYPE].setSpecialType(PrimitiveNode.MULTICUT); metalWellContactNodes[N_TYPE].setSpecialValues(new double [] {2, 2, 1.5, 1.5, 3, 3}); metalWellContactNodes[N_TYPE].setMinSize(17, 17, "4.2, 6.2, 7.3"); /********************** RPO Resistor-Node ********************************/ double polySelectOffX = 1.8; /* NP.C.3 */ // double rpoViaOffX = 2.2 /* RPO.C.2 */; double polyCutSize = 2.2; /* page 28 */ double resistorViaOff = 1.0; /* page 28 */ double resistorConW = polyCutSize + 2*resistorViaOff /*contact width viaW + 2*viaS = (2.2 + 2*1). It must be 1xN */; double resistorConH = resistorConW /*contact height*/; double resistorOffX = resistorConW + polySelectOffX + 1.2 /*0.22um-0.1 (poly extension in contact)*/; double resistorW = 20 + 2*resistorOffX; double resistorOffY = 2.2 /* RPO.C.2*/; double resistorH = 2*resistorOffY + resistorConH; // double resistorM1Off = 0.5 /*poly surround in poly contact */; // double resistorPolyOffX = 2.2; /* page 28 */ // double resistorV2OffX = -polyCutSize - 0.7 + resistorPolyX + resistorConW; // double resistorPortOffX = resistorPolyX + (resistorConW-polyCutSize)/2; // for the port double resistorM1Off = resistorViaOff - 0.6; // 0.6 = M.E.2 double resistorM1W = resistorConW-2*resistorM1Off; double resistorM1OffX = resistorM1Off + polySelectOffX; double resistorM1OffY = resistorM1Off + resistorOffY; double resistorV1OffX = resistorViaOff + polySelectOffX; double resistorV1OffY = resistorOffY + (resistorConH-polyCutSize)/2; rpoResistorNodes = new PrimitiveNode[2]; for (int i = 0; i < rpoResistorNodes.length; i++) { rpoResistorNodes[i] = PrimitiveNode.newInstance(stdNames[i]+"-Poly-RPO-Resistor", this, resistorW, resistorH, new SizeOffset(resistorOffX, resistorOffX, resistorOffY, resistorOffY), new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(polySelectOffX), EdgeV.fromBottom(resistorOffY)), new Technology.TechPoint(EdgeH.fromRight(polySelectOffX), EdgeV.fromTop(resistorOffY))}), new Technology.NodeLayer(silicideBlock_lay, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorOffX), EdgeV.makeBottomEdge()), new Technology.TechPoint(EdgeH.fromRight(resistorOffX), EdgeV.makeTopEdge())}), new Technology.NodeLayer(selectLayers[i], -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.makeLeftEdge(), EdgeV.fromBottom(0.2)), new Technology.TechPoint(EdgeH.makeRightEdge(), EdgeV.fromTop(0.2))}), // Left contact new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorM1OffX+resistorM1W), EdgeV.fromTop(resistorM1OffY))}), // left via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}), // Right contact new Technology.NodeLayer(metalLayers[0], 1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX+resistorM1W), EdgeV.fromBottom(resistorM1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorM1OffX), EdgeV.fromTop(resistorM1OffY))}), // right via new Technology.NodeLayer(polyCutLayer, -1, Poly.Type.FILLED, Technology.NodeLayer.BOX, new Technology.TechPoint [] { new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromBottom(resistorV1OffY)), new Technology.TechPoint(EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY+polyCutSize))}) }); rpoResistorNodes[i].addPrimitivePorts(new PrimitivePort [] { // left port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "left-rpo", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromLeft(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)), // right port PrimitivePort.newInstance(this, rpoResistorNodes[i], new ArcProto[] {poly1_arc, metalArcs[0]}, "right-rpo", 0,180, 1, PortCharacteristic.UNKNOWN, EdgeH.fromRight(resistorV1OffX), EdgeV.fromBottom(resistorV1OffY), EdgeH.fromRight(resistorV1OffX+polyCutSize), EdgeV.fromTop(resistorV1OffY)) }); rpoResistorNodes[i].setFunction(PrimitiveNode.Function.PRESIST); rpoResistorNodes[i].setHoldsOutline(); rpoResistorNodes[i].setSpecialType(PrimitiveNode.POLYGONAL); } /** Metal-1-Node */ metal1Node_node = PrimitiveNode.newInstance("Metal-1-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[0], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal1Node_node, new ArcProto[] {metalArcs[0]}, "metal-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal1Node_node.setFunction(PrimitiveNode.Function.NODE); metal1Node_node.setHoldsOutline(); metal1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-2-Node */ metal2Node_node = PrimitiveNode.newInstance("Metal-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[1], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal2Node_node, new ArcProto[] {metalArcs[1]}, "metal-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal2Node_node.setFunction(PrimitiveNode.Function.NODE); metal2Node_node.setHoldsOutline(); metal2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-3-Node */ metal3Node_node = PrimitiveNode.newInstance("Metal-3-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[2], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal3Node_node, new ArcProto[] {metalArcs[2]}, "metal-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal3Node_node.setFunction(PrimitiveNode.Function.NODE); metal3Node_node.setHoldsOutline(); metal3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-4-Node */ metal4Node_node = PrimitiveNode.newInstance("Metal-4-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[3], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal4Node_node, new ArcProto[] {metalArcs[3]}, "metal-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal4Node_node.setFunction(PrimitiveNode.Function.NODE); metal4Node_node.setHoldsOutline(); metal4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Metal-5-Node */ metal5Node_node = PrimitiveNode.newInstance("Metal-5-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[4], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal5Node_node, new ArcProto[] {metalArcs[4]}, "metal-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal5Node_node.setFunction(PrimitiveNode.Function.NODE); metal5Node_node.setHoldsOutline(); metal5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal5Node_node.setNotUsed(); /** Metal-6-Node */ metal6Node_node = PrimitiveNode.newInstance("Metal-6-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(metalLayers[5], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); metal6Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, metal6Node_node, new ArcProto[] {metalArcs[5]}, "metal-6", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); metal6Node_node.setFunction(PrimitiveNode.Function.NODE); metal6Node_node.setHoldsOutline(); metal6Node_node.setSpecialType(PrimitiveNode.POLYGONAL); metal6Node_node.setNotUsed(); /** Polysilicon-1-Node */ poly1Node_node = PrimitiveNode.newInstance("Polysilicon-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly1Node_node, new ArcProto[] {poly1_arc}, "polysilicon-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); poly1Node_node.setFunction(PrimitiveNode.Function.NODE); poly1Node_node.setHoldsOutline(); poly1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-2-Node */ poly2Node_node = PrimitiveNode.newInstance("Polysilicon-2-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(poly2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); poly2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, poly2Node_node, new ArcProto[] {poly2_arc}, "polysilicon-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); poly2Node_node.setFunction(PrimitiveNode.Function.NODE); poly2Node_node.setHoldsOutline(); poly2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); poly2Node_node.setNotUsed(); /** P-Active-Node */ pActiveNode_node = PrimitiveNode.newInstance("P-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); pActiveNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveNode_node.setHoldsOutline(); pActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Active-Node */ nActiveNode_node = PrimitiveNode.newInstance("N-Active-Node", this, 3.0, 3.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nActiveNode_node, new ArcProto[] {active_arc, activeArcs[P_TYPE], activeArcs[N_TYPE]}, "active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1.5), EdgeV.fromBottom(1.5), EdgeH.fromRight(1.5), EdgeV.fromTop(1.5)) }); nActiveNode_node.setFunction(PrimitiveNode.Function.NODE); nActiveNode_node.setHoldsOutline(); nActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Select-Node */ pSelectNode_node = PrimitiveNode.newInstance("P-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pSelectNode_node.setFunction(PrimitiveNode.Function.NODE); pSelectNode_node.setHoldsOutline(); pSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Select-Node */ nSelectNode_node = PrimitiveNode.newInstance("N-Select-Node", this, 4.0, 4.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(selectLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nSelectNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nSelectNode_node, new ArcProto[0], "select", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); nSelectNode_node.setFunction(PrimitiveNode.Function.NODE); nSelectNode_node.setHoldsOutline(); nSelectNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** PolyCut-Node */ polyCutNode_node = PrimitiveNode.newInstance("Poly-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCutLayer, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCutNode_node, new ArcProto[0], "polycut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCutNode_node.setFunction(PrimitiveNode.Function.NODE); polyCutNode_node.setHoldsOutline(); polyCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** ActiveCut-Node */ activeCutNode_node = PrimitiveNode.newInstance("Active-Cut-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(activeCut_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); activeCutNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, activeCutNode_node, new ArcProto[0], "activecut", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); activeCutNode_node.setFunction(PrimitiveNode.Function.NODE); activeCutNode_node.setHoldsOutline(); activeCutNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-1-Node */ via1Node_node = PrimitiveNode.newInstance("Via-1-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via1_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via1Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via1Node_node, new ArcProto[0], "via-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via1Node_node.setFunction(PrimitiveNode.Function.NODE); via1Node_node.setHoldsOutline(); via1Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-2-Node */ via2Node_node = PrimitiveNode.newInstance("Via-2-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via2_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via2Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via2Node_node, new ArcProto[0], "via-2", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via2Node_node.setFunction(PrimitiveNode.Function.NODE); via2Node_node.setHoldsOutline(); via2Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-3-Node */ via3Node_node = PrimitiveNode.newInstance("Via-3-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via3_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via3Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via3Node_node, new ArcProto[0], "via-3", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via3Node_node.setFunction(PrimitiveNode.Function.NODE); via3Node_node.setHoldsOutline(); via3Node_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Via-4-Node */ via4Node_node = PrimitiveNode.newInstance("Via-4-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via4_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via4Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via4Node_node, new ArcProto[0], "via-4", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via4Node_node.setFunction(PrimitiveNode.Function.NODE); via4Node_node.setHoldsOutline(); via4Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via4Node_node.setNotUsed(); /** Via-5-Node */ via5Node_node = PrimitiveNode.newInstance("Via-5-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(via5_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); via5Node_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, via5Node_node, new ArcProto[0], "via-5", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); via5Node_node.setFunction(PrimitiveNode.Function.NODE); via5Node_node.setHoldsOutline(); via5Node_node.setSpecialType(PrimitiveNode.POLYGONAL); via5Node_node.setNotUsed(); /** P-Well-Node */ pWellNode_node = PrimitiveNode.newInstance("P-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[P_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); pWellNode_node.setFunction(PrimitiveNode.Function.NODE); pWellNode_node.setHoldsOutline(); pWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** N-Well-Node */ nWellNode_node = PrimitiveNode.newInstance("N-Well-Node", this, 12.0, 12.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(wellLayers[N_TYPE], 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); nWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, nWellNode_node, new ArcProto[] {activeArcs[P_TYPE]}, "well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(3), EdgeV.fromBottom(3), EdgeH.fromRight(3), EdgeV.fromTop(3)) }); nWellNode_node.setFunction(PrimitiveNode.Function.NODE); nWellNode_node.setHoldsOutline(); nWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Passivation-Node */ passivationNode_node = PrimitiveNode.newInstance("Passivation-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(passivation_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); passivationNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, passivationNode_node, new ArcProto[0], "passivation", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); passivationNode_node.setFunction(PrimitiveNode.Function.NODE); passivationNode_node.setHoldsOutline(); passivationNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Pad-Frame-Node */ padFrameNode_node = PrimitiveNode.newInstance("Pad-Frame-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(padFrame_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); padFrameNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, padFrameNode_node, new ArcProto[0], "pad-frame", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); padFrameNode_node.setFunction(PrimitiveNode.Function.NODE); padFrameNode_node.setHoldsOutline(); padFrameNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Poly-Cap-Node */ polyCapNode_node = PrimitiveNode.newInstance("Poly-Cap-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(polyCap_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyCapNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyCapNode_node, new ArcProto[0], "poly-cap", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); polyCapNode_node.setFunction(PrimitiveNode.Function.NODE); polyCapNode_node.setHoldsOutline(); polyCapNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** P-Active-Well-Node */ pActiveWellNode_node = PrimitiveNode.newInstance("P-Active-Well-Node", this, 8.0, 8.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(pActiveWell_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); pActiveWellNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, pActiveWellNode_node, new ArcProto[0], "p-active-well", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); pActiveWellNode_node.setFunction(PrimitiveNode.Function.NODE); pActiveWellNode_node.setHoldsOutline(); pActiveWellNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Polysilicon-1-Transistor-Node */ polyTransistorNode_node = PrimitiveNode.newInstance("Transistor-Poly-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(transistorPoly_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); polyTransistorNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, polyTransistorNode_node, new ArcProto[] {poly1_arc}, "trans-poly-1", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.fromLeft(1), EdgeV.fromBottom(1), EdgeH.fromRight(1), EdgeV.fromTop(1)) }); polyTransistorNode_node.setFunction(PrimitiveNode.Function.NODE); polyTransistorNode_node.setHoldsOutline(); polyTransistorNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Silicide-Block-Node */ silicideBlockNode_node = PrimitiveNode.newInstance("Silicide-Block-Node", this, 2.0, 2.0, null, new Technology.NodeLayer [] { new Technology.NodeLayer(silicideBlock_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); silicideBlockNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, silicideBlockNode_node, new ArcProto[] {poly1_arc}, "silicide-block", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); silicideBlockNode_node.setFunction(PrimitiveNode.Function.NODE); silicideBlockNode_node.setHoldsOutline(); silicideBlockNode_node.setSpecialType(PrimitiveNode.POLYGONAL); /** Thick-Active-Node */ thickActiveNode_node = PrimitiveNode.newInstance("Thick-Active-Node", this, 4.0, 4.0, null, // 4.0 is given by rule 24.1 new Technology.NodeLayer [] { new Technology.NodeLayer(thickActive_lay, 0, Poly.Type.FILLED, Technology.NodeLayer.BOX, Technology.TechPoint.makeFullBox()) }); thickActiveNode_node.addPrimitivePorts(new PrimitivePort [] { PrimitivePort.newInstance(this, thickActiveNode_node, new ArcProto[] {poly1_arc}, "thick-active", 0,180, 0, PortCharacteristic.UNKNOWN, EdgeH.makeLeftEdge(), EdgeV.makeBottomEdge(), EdgeH.makeRightEdge(), EdgeV.makeTopEdge()) }); thickActiveNode_node.setFunction(PrimitiveNode.Function.NODE); thickActiveNode_node.setHoldsOutline(); thickActiveNode_node.setSpecialType(PrimitiveNode.POLYGONAL); // The pure layer nodes metalLayers[0].setPureLayerNode(metal1Node_node); // Metal-1 metalLayers[1].setPureLayerNode(metal2Node_node); // Metal-2 metalLayers[2].setPureLayerNode(metal3Node_node); // Metal-3 metalLayers[3].setPureLayerNode(metal4Node_node); // Metal-4 metalLayers[4].setPureLayerNode(metal5Node_node); // Metal-5 metalLayers[5].setPureLayerNode(metal6Node_node); // Metal-6 poly1_lay.setPureLayerNode(poly1Node_node); // Polysilicon-1 poly2_lay.setPureLayerNode(poly2Node_node); // Polysilicon-2 activeLayers[P_TYPE].setPureLayerNode(pActiveNode_node); // P-Active activeLayers[N_TYPE].setPureLayerNode(nActiveNode_node); // N-Active selectLayers[P_TYPE].setPureLayerNode(pSelectNode_node); // P-Select selectLayers[N_TYPE].setPureLayerNode(nSelectNode_node); // N-Select wellLayers[P_TYPE].setPureLayerNode(pWellNode_node); // P-Well wellLayers[N_TYPE].setPureLayerNode(nWellNode_node); // N-Well polyCutLayer.setPureLayerNode(polyCutNode_node); // Poly-Cut activeCut_lay.setPureLayerNode(activeCutNode_node); // Active-Cut via1_lay.setPureLayerNode(via1Node_node); // Via-1 via2_lay.setPureLayerNode(via2Node_node); // Via-2 via3_lay.setPureLayerNode(via3Node_node); // Via-3 via4_lay.setPureLayerNode(via4Node_node); // Via-4 via5_lay.setPureLayerNode(via5Node_node); // Via-5 passivation_lay.setPureLayerNode(passivationNode_node); // Passivation transistorPoly_lay.setPureLayerNode(polyTransistorNode_node); // Transistor-Poly polyCap_lay.setPureLayerNode(polyCapNode_node); // Poly-Cap pActiveWell_lay.setPureLayerNode(pActiveWellNode_node); // P-Active-Well silicideBlock_lay.setPureLayerNode(silicideBlockNode_node); // Silicide-Block thickActive_lay.setPureLayerNode(thickActiveNode_node); // Thick-Active padFrame_lay.setPureLayerNode(padFrameNode_node); // Pad-Frame // Information for palette int maxY = metalArcs.length + activeArcs.length + 1 /* poly*/ + 1 /* trans */ + 1 /*misc*/ + 1 /* well */; nodeGroups = new Object[maxY][3]; int count = 0; String[] shortNames = {"p", "n"}; List tmp; // Transistor nodes first for (int i = 0; i < transistorNodes.length; i++) { tmp = new ArrayList(2); String tmpVar = shortNames[i]+"Mos"; tmp.add(makeNodeInst(transistorNodes[i], transistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(thickTransistorNodes[i], thickTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); tmp.add(makeNodeInst(scalableTransistorNodes[i], scalableTransistorNodes[i].getFunction(), 0, true, tmpVar, 9)); nodeGroups[count][i+1] = tmp; } // Well second count++; for (int i = 0; i < metalWellContactNodes.length; i++) { String tmpVar = shortNames[i]+"Well"; nodeGroups[count][i+1] = makeNodeInst(metalWellContactNodes[i], metalWellContactNodes[i].getFunction(), 0, true, tmpVar, 5.5); } // RPO resistors for (int i = 0; i < rpoResistorNodes.length; i++) { String tmpVar = shortNames[i]+"R"; tmp = new ArrayList(1); tmp.add(makeNodeInst(rpoResistorNodes[i], rpoResistorNodes[i].getFunction(), 0, true, tmpVar, 10)); nodeGroups[i][0] = tmp; } // Active/Well first for (int i = 0; i < activeArcs.length; i++) { nodeGroups[++count][0] = activeArcs[i]; nodeGroups[count][1] = activePinNodes[i]; String tmpVar = shortNames[i]+"Act"; nodeGroups[count][2] = makeNodeInst(metalActiveContactNodes[i], metalActiveContactNodes[i].getFunction(), 0, true, tmpVar, 5.55); } // Poly-related node insts nodeGroups[++count][0] = poly1_arc; nodeGroups[count][1] = poly1Pin_node; nodeGroups[count][2] = metal1Poly1Contact_node; // MXMY contacts for (int i = 0; i < metalArcs.length; i++) { nodeGroups[++count][0] = metalArcs[i]; nodeGroups[count][1] = metalPinNodes[i]; nodeGroups[count][2] = (i < metalArcs.length - 1) ? metalContactNodes[i] : null; } // On the side nodeGroups[++count][0] = "Pure"; nodeGroups[count][1] = "Misc."; nodeGroups[count][2] = "Cell"; }
diff --git a/src/main/java/net/aufdemrand/denizen/listeners/AbstractListener.java b/src/main/java/net/aufdemrand/denizen/listeners/AbstractListener.java index 6bc4c6a84..d6fa57f0c 100644 --- a/src/main/java/net/aufdemrand/denizen/listeners/AbstractListener.java +++ b/src/main/java/net/aufdemrand/denizen/listeners/AbstractListener.java @@ -1,186 +1,186 @@ package net.aufdemrand.denizen.listeners; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.aufdemrand.denizen.objects.aH; import net.aufdemrand.denizen.objects.dNPC; import net.aufdemrand.denizen.objects.dPlayer; import net.aufdemrand.denizen.objects.dScript; import org.bukkit.Bukkit; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.utilities.debugging.dB; public abstract class AbstractListener { protected Denizen denizen; protected String type; public String id; protected dPlayer player; protected dScript scriptName; protected dNPC npc; protected Map<String, Object> savable = new HashMap<String, Object>(); public AbstractListener() { this.denizen = (Denizen) Bukkit.getServer().getPluginManager().getPlugin("Denizen"); } public void build(dPlayer player, String listenerId, String listenerType, List<aH.Argument> args, dScript finishScript, dNPC npc) { this.player = player; this.id = listenerId; this.type = listenerType; this.scriptName = finishScript; this.npc = npc; onBuild(args); save(); constructed(); } public void cancel() { onCancel(); denizen.getListenerRegistry().cancel(player, id); deconstructed(); } public abstract void constructed(); public abstract void deconstructed(); public void finish() { onFinish(); denizen.getListenerRegistry().finish(player, npc, id, scriptName); deconstructed(); } /** * Gets an Object that was store()d away. * * @param key * the name (key) of the Object requested * @return the Object associated with the key * */ public Object get(String key) { return denizen.getSaves().get("Listeners." + player.getName() + "." + id + "." + key); } public String getListenerId() { return id != null ? id : ""; } public String getListenerType() { return type != null ? type : ""; } public void load(dPlayer player, dNPC npc, String id, String listenerType) { this.player = player; this.id = id; this.type = listenerType; this.scriptName = dScript.valueOf((String) get("Finish Script")); this.npc = npc; try { onLoad(); } catch (Exception e) { dB.echoError("Problem loading saved listener '" + id + "' for " + player.getName() + "!"); } constructed(); } /** * Method to handle building a new quest listener List<String> of arguments. * Most likely called from a LISTEN dScript command. The player and id fields * are non-null at this point. * * @param args * a list of dScript arguments * */ public abstract void onBuild(List<aH.Argument> args); public abstract void onCancel(); public abstract void onFinish(); /** * Called when a Player logs on if an instance of this quest listener was saved * with progress. Any variables that were saved with the store(stringKey, object) method * should be called and restored. * */ public abstract void onLoad(); /** * When a Player logs off, the quest listener's progress is stored to saves.yml. * This method should use the store(stringKey, object) method to save the fields needed to * successfully reload the current state of this quest listener when the onLoad() * method is called. The fields for player, type, and id are done automatically. * */ public abstract void onSave(); /** * Sums up the current status of a this AbstractListenerInstance in a way that would be * useful by itself to a Player or Console administrator. * * Called by the '/denizen listener --report id' bukkit command. * * This should include all applicable variables when reporting. Suggested format would * follow suit with core Listeners. For example: * * return player.getName() + " currently has quest listener '" + id * + "' active and must kill " + Arrays.toString(targets.toArray()) * + " '" + type.name() + "'(s). Current progress '" + currentKills * + "/" + quantity + "'."; * * Output: * aufdemrand currently has quest listener 'example_quest' active and must kill * '[ZOMBIE, SKELETON] ENTITY'(s). Current progress '10/15'. * * Note: This is not intended to be a 'Quest Log' for a Player, rather is used when * administrators/server operators are checking up on this Listener. Ideally, * that kind of information should be handled with the use of replaceable tags. * * @return a 'formatted' String that contains current progress * */ public abstract String report(); public void save() { denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Listener Type", type); denizen.getSaves().set("Listeners." + player.getName() + "." + id - + ".Finish Script", scriptName); + + ".Finish Script", scriptName.toString()); if (npc != null) denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Linked NPCID", npc.getId()); onSave(); try { if (!savable.isEmpty()) for (Entry<String, Object> entry : savable.entrySet()) denizen.getSaves().set("Listeners." + player.getName() + "." + id + "." + entry.getKey(), entry.getValue()); } catch (Exception e) { dB.echoError("Problem saving listener '" + id + "' for " + player.getName() + "!"); } deconstructed(); } /** * Stores a field away for retrieving later. Should be used in the onSave() method. * */ public void store(String key, Object object) { savable.put(key, object); } }
true
true
public void save() { denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Listener Type", type); denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Finish Script", scriptName); if (npc != null) denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Linked NPCID", npc.getId()); onSave(); try { if (!savable.isEmpty()) for (Entry<String, Object> entry : savable.entrySet()) denizen.getSaves().set("Listeners." + player.getName() + "." + id + "." + entry.getKey(), entry.getValue()); } catch (Exception e) { dB.echoError("Problem saving listener '" + id + "' for " + player.getName() + "!"); } deconstructed(); }
public void save() { denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Listener Type", type); denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Finish Script", scriptName.toString()); if (npc != null) denizen.getSaves().set("Listeners." + player.getName() + "." + id + ".Linked NPCID", npc.getId()); onSave(); try { if (!savable.isEmpty()) for (Entry<String, Object> entry : savable.entrySet()) denizen.getSaves().set("Listeners." + player.getName() + "." + id + "." + entry.getKey(), entry.getValue()); } catch (Exception e) { dB.echoError("Problem saving listener '" + id + "' for " + player.getName() + "!"); } deconstructed(); }
diff --git a/src/java/net/sf/picard/sam/MergeSamFiles.java b/src/java/net/sf/picard/sam/MergeSamFiles.java index 36e5c53..cf5ee1c 100644 --- a/src/java/net/sf/picard/sam/MergeSamFiles.java +++ b/src/java/net/sf/picard/sam/MergeSamFiles.java @@ -1,228 +1,225 @@ /* * The MIT License * * Copyright (c) 2009 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.sam; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.picard.util.Log; import net.sf.picard.PicardException; import net.sf.samtools.*; /** * Reads a SAM or BAM file and combines the output to one file * * @author Tim Fennell */ public class MergeSamFiles extends CommandLineProgram { private static final Log log = Log.getInstance(MergeSamFiles.class); // Usage and parameters @Usage public String USAGE = "Merges multiple SAM/BAM files into one file.\n"; @Option(shortName="I", doc="SAM or BAM input file", minElements=1) public List<File> INPUT = new ArrayList<File>(); @Option(shortName="O", doc="SAM or BAM file to write merged result to") public File OUTPUT; @Option(shortName=StandardOptionDefinitions.SORT_ORDER_SHORT_NAME, doc="Sort order of output file", optional=true) public SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate; @Option(doc="If true, assume that the input files are in the same sort order as the requested output sort order, even if their headers say otherwise.", shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME) public boolean ASSUME_SORTED = false; @Option(shortName="MSD", doc="Merge the seqeunce dictionaries", optional=true) public boolean MERGE_SEQUENCE_DICTIONARIES = false; @Option(doc="Option to enable a simple two-thread producer consumer version of the merge algorithm that " + "uses one thread to read and merge the records from the input files and another thread to encode, " + "compress and write to disk the output file. The threaded version uses about 20% more CPU and decreases " + "runtime by ~20% when writing out a compressed BAM file.") public boolean USE_THREADING = false; @Option(doc="Comment(s) to include in the merged output file's header.", optional=true, shortName="CO") public List<String> COMMENT = new ArrayList<String>(); private static final int PROGRESS_INTERVAL = 1000000; /** Required main method implementation. */ public static void main(final String[] argv) { System.exit(new MergeSamFiles().instanceMain(argv)); } /** Combines multiple SAM/BAM files into one. */ @Override protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); - final MergingSamRecordIterator iterator; - final SAMFileWriter out; + final boolean presorted; + final SAMFileHeader.SortOrder headerMergerSortOrder; + final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); - final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SORT_ORDER, headers, MERGE_SEQUENCE_DICTIONARIES); - iterator = new MergingSamRecordIterator(headerMerger, readers, ASSUME_SORTED); - final SAMFileHeader header = headerMerger.getMergedHeader(); - for (String comment : COMMENT) { - header.addComment(comment); - } - out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, OUTPUT); + headerMergerSortOrder = SORT_ORDER; + mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; + presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); - final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SAMFileHeader.SortOrder.unsorted, - headers, - MERGE_SEQUENCE_DICTIONARIES); - iterator = new MergingSamRecordIterator(headerMerger, readers, false); - final SAMFileHeader header = headerMerger.getMergedHeader(); - header.setSortOrder(SORT_ORDER); - for (String comment : COMMENT) { - header.addComment(comment); - } - out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, false, OUTPUT); + headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; + mergingSamRecordIteratorAssumeSorted = false; + presorted = false; + } + final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); + final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); + final SAMFileHeader header = headerMerger.getMergedHeader(); + for (String comment : COMMENT) { + header.addComment(comment); } + final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; } @Override protected String[] customCommandLineValidation() { if (CREATE_INDEX && SORT_ORDER != SAMFileHeader.SortOrder.coordinate) { return new String[]{"Can't CREATE_INDEX unless SORT_ORDER is coordinate"}; } return null; } }
false
true
protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final MergingSamRecordIterator iterator; final SAMFileWriter out; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SORT_ORDER, headers, MERGE_SEQUENCE_DICTIONARIES); iterator = new MergingSamRecordIterator(headerMerger, readers, ASSUME_SORTED); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, OUTPUT); } else { log.info("Sorting input files using temp directory " + TMP_DIR); final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(SAMFileHeader.SortOrder.unsorted, headers, MERGE_SEQUENCE_DICTIONARIES); iterator = new MergingSamRecordIterator(headerMerger, readers, false); final SAMFileHeader header = headerMerger.getMergedHeader(); header.setSortOrder(SORT_ORDER); for (String comment : COMMENT) { header.addComment(comment); } out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, false, OUTPUT); } // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; }
protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final boolean presorted; final SAMFileHeader.SortOrder headerMergerSortOrder; final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); headerMergerSortOrder = SORT_ORDER; mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; mergingSamRecordIteratorAssumeSorted = false; presorted = false; } final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; }
diff --git a/src/com/philiptorchinsky/TimeAppe/MainActivity.java b/src/com/philiptorchinsky/TimeAppe/MainActivity.java index 158d7be..33f8dcc 100644 --- a/src/com/philiptorchinsky/TimeAppe/MainActivity.java +++ b/src/com/philiptorchinsky/TimeAppe/MainActivity.java @@ -1,93 +1,93 @@ package com.philiptorchinsky.TimeAppe; import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends ListActivity { /** * Called when the activity is first created. */ static public boolean isTest = false; private DBAdapter dh; private Adapter notes; public ArrayList<Item> list = new ArrayList<Item>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dh = new DBAdapter (this); dh.open(); // dh.destroy(); // dh.close(); // // dh = new DBAdapter (this); - dh.insert("TeamCity training", "inactive", 0,0); - dh.insert("Android Study", "inactive", 0,0); - dh.insert("FreelancersFeed", "inactive",0,0); +// dh.insert("TeamCity training", "inactive", 0,0); +// dh.insert("Android Study", "inactive", 0,0); +// dh.insert("FreelancersFeed", "inactive",0,0); // GET ROWS Cursor c = dh.getAll(); - int i = 2; + int i = 0; c.moveToFirst(); if (!c.isAfterLast()) { do { String project = c.getString(1); String status = c.getString(2); long secondsSpent = c.getLong(3); long lastactivated = c.getLong(4); Item newitem = new Item(project, status, secondsSpent, lastactivated); list.add(newitem); } while (c.moveToNext()); } notes = new Adapter (this,list); setContentView(R.layout.main); setListAdapter(notes); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Item item = (Item) getListAdapter().getItem(position); String project = item.getProject(); String status = item.getStatus(); long secondsSpent = item.getSecondsSpent(); long lastActivated = item.getLastactivated(); if (status.equalsIgnoreCase("active")) { status = "inactive"; item.setStatus(status); long spentThisTime = System.currentTimeMillis() - lastActivated; item.setSecondsSpent(secondsSpent + spentThisTime); list.set((int)id,item); dh.updateSpentTimeByProject(project,status,secondsSpent + spentThisTime); // Toast.makeText(this, project + " selected. Now " + (secondsSpent + spentThisTime)/1000.0, Toast.LENGTH_LONG).show(); } else { status = "active"; item.setStatus(status); lastActivated = System.currentTimeMillis(); item.setLastactivated(lastActivated); list.set((int)id,item); dh.updateActivatedByProject(project,status,lastActivated); } notes.notifyDataSetChanged(); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dh = new DBAdapter (this); dh.open(); // dh.destroy(); // dh.close(); // // dh = new DBAdapter (this); dh.insert("TeamCity training", "inactive", 0,0); dh.insert("Android Study", "inactive", 0,0); dh.insert("FreelancersFeed", "inactive",0,0); // GET ROWS Cursor c = dh.getAll(); int i = 2; c.moveToFirst(); if (!c.isAfterLast()) { do { String project = c.getString(1); String status = c.getString(2); long secondsSpent = c.getLong(3); long lastactivated = c.getLong(4); Item newitem = new Item(project, status, secondsSpent, lastactivated); list.add(newitem); } while (c.moveToNext()); } notes = new Adapter (this,list); setContentView(R.layout.main); setListAdapter(notes); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dh = new DBAdapter (this); dh.open(); // dh.destroy(); // dh.close(); // // dh = new DBAdapter (this); // dh.insert("TeamCity training", "inactive", 0,0); // dh.insert("Android Study", "inactive", 0,0); // dh.insert("FreelancersFeed", "inactive",0,0); // GET ROWS Cursor c = dh.getAll(); int i = 0; c.moveToFirst(); if (!c.isAfterLast()) { do { String project = c.getString(1); String status = c.getString(2); long secondsSpent = c.getLong(3); long lastactivated = c.getLong(4); Item newitem = new Item(project, status, secondsSpent, lastactivated); list.add(newitem); } while (c.moveToNext()); } notes = new Adapter (this,list); setContentView(R.layout.main); setListAdapter(notes); }
diff --git a/src/com/redhat/ceylon/compiler/codegen/StatementGen.java b/src/com/redhat/ceylon/compiler/codegen/StatementGen.java index 18b949309..a838aee92 100644 --- a/src/com/redhat/ceylon/compiler/codegen/StatementGen.java +++ b/src/com/redhat/ceylon/compiler/codegen/StatementGen.java @@ -1,308 +1,310 @@ package com.redhat.ceylon.compiler.codegen; import static com.sun.tools.javac.code.Flags.FINAL; import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; public class StatementGen extends GenPart { public StatementGen(Gen2 gen) { super(gen); } class StatementVisitor extends Visitor implements NaturalVisitor { final ListBuffer<JCStatement> stmts; final Tree.ClassOrInterface cdecl; StatementVisitor(Tree.ClassOrInterface cdecl, ListBuffer<JCStatement> stmts) { this.stmts = stmts; this.cdecl = cdecl; } public ListBuffer<JCStatement> stmts() { return stmts; } public void visit(Tree.InvocationExpression expr) { stmts.append(at(expr).Exec(gen.expressionGen.convert(expr))); } public void visit(Tree.Return ret) { stmts.append(convert(ret)); } public void visit(Tree.IfStatement stat) { stmts.append(convert(cdecl, stat)); } public void visit(Tree.WhileStatement stat) { stmts.append(convert(cdecl, stat)); } public void visit(Tree.ForStatement stat) { stmts.append(convert(cdecl, stat)); } public void visit(Tree.AttributeDeclaration decl) { for (JCTree def : gen.classGen.convert(cdecl, decl)) stmts.append((JCStatement) def); } // FIXME: not sure why we don't have just an entry for Tree.Term here... public void visit(Tree.OperatorExpression op) { stmts.append(at(op).Exec(gen.expressionGen.convertExpression(op))); } public void visit(Tree.Expression tree) { stmts.append(at(tree).Exec(gen.expressionGen.convertExpression(tree))); } public void visit(Tree.MethodDefinition decl) { final ListBuffer<JCTree> defs = new ListBuffer<JCTree>(); gen.classGen.methodClass(cdecl, decl, defs, false); for (JCTree def : defs.toList()) { JCClassDecl innerDecl = (JCClassDecl) def; stmts.append(innerDecl); JCExpression id = make().Ident(innerDecl.name); stmts.append(at(decl).VarDef(make().Modifiers(FINAL), names().fromString(decl.getIdentifier().getText()), id, at(decl).NewClass(null, null, id, List.<JCExpression> nil(), null))); } } // FIXME: I think those should just go in convertExpression no? public void visit(Tree.PostfixOperatorExpression expr) { stmts.append(at(expr).Exec(gen.expressionGen.convert(expr))); } public void visit(Tree.PrefixOperatorExpression expr) { stmts.append(at(expr).Exec(gen.expressionGen.convert(expr))); } public void visit(Tree.ExpressionStatement tree) { stmts.append(at(tree).Exec(gen.expressionGen.convertExpression(tree.getExpression()))); } } public JCBlock convert(Tree.ClassOrInterface cdecl, Tree.Block block) { return block == null ? null : at(block).Block(0, convertStmts(cdecl, block.getStatements())); } private List<JCStatement> convertStmts(Tree.ClassOrInterface cdecl, java.util.List<Tree.Statement> list) { final ListBuffer<JCStatement> buf = new ListBuffer<JCStatement>(); StatementVisitor v = new StatementVisitor(cdecl, buf); for (Tree.Statement stmt : list) stmt.visit(v); return buf.toList(); } private JCStatement convert(Tree.ClassOrInterface cdecl, Tree.IfStatement stmt) { JCBlock thenPart = convert(cdecl, stmt.getIfClause().getBlock()); JCBlock elsePart = stmt.getElseClause() != null ? convert(cdecl, stmt.getElseClause().getBlock()) : null; return convertCondition(stmt.getIfClause().getCondition(), JCTree.IF, thenPart, elsePart); } private JCStatement convert(Tree.ClassOrInterface cdecl, Tree.WhileStatement stmt) { JCBlock thenPart = convert(cdecl, stmt.getWhileClause().getBlock()); return convertCondition(stmt.getWhileClause().getCondition(), JCTree.WHILELOOP, thenPart, null); } private JCStatement convertCondition(Tree.Condition cond, int tag, JCBlock thenPart, JCBlock elsePart) { if (cond instanceof Tree.ExistsCondition) { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; Tree.Identifier name = exists.getVariable().getIdentifier(); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedExists")); Name tmp2 = names().fromString(name.getText()); JCExpression type; if (exists.getVariable().getType() == null) { type = makeIdent(syms().ceylonAnyType); } else { type = gen.variableType(exists.getVariable().getType(), null); } JCExpression expr; if (exists.getExpression() == null) { expr = at(cond).Ident(tmp2); } else { expr = gen.expressionGen.convertExpression(exists.getExpression()); } expr = at(cond).Apply(null, at(cond).Select(expr, names().fromString("$internalErasedExists")), List.<JCExpression> nil()); // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, type, exists.getVariable().getType() == null ? expr : null); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).Ident(tmp)); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCTree.JCBinary test = at(cond).Binary(JCTree.NE, assignment, make().Literal(TypeTags.BOT, null)); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.IsCondition) { // FIXME: This code has a lot in common with the ExistsExpression // above, but it has a niggling few things that are different. // It needs to be refactored. Tree.IsCondition isExpr = (Tree.IsCondition) cond; Tree.Identifier name = isExpr.getVariable().getIdentifier(); JCExpression type = gen.variableType(isExpr.getType(), null); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedIs")); Name tmp2 = names().fromString(name.getText()); JCExpression expr; if (isExpr.getExpression() == null) { expr = convert(name); } else { expr = gen.expressionGen.convertExpression(isExpr.getExpression()); } // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, makeIdent(syms().ceylonAnyType), expr); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).TypeCast(type, at(cond).Ident(tmp))); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCExpression test = at(cond).TypeTest(assignment, type); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; JCExpression test = gen.expressionGen.convertExpression(booleanCondition.getExpression()); - test = at(cond).Binary(JCTree.EQ, test, makeIdent("ceylon", "language", "_true", "value")); + JCExpression trueValue = at(cond).Apply(List.<JCTree.JCExpression>nil(), + makeIdent("ceylon", "language", "$true", "getTrue"), List.<JCTree.JCExpression>nil()); + test = at(cond).Binary(JCTree.EQ, test, trueValue); JCStatement result; switch (tag) { case JCTree.IF: result = at(cond).If(test, thenPart, elsePart); break; case JCTree.WHILELOOP: assert elsePart == null; result = at(cond).WhileLoop(test, thenPart); break; default: throw new RuntimeException(); } return result; } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } } private JCStatement convert(Tree.ClassOrInterface cdecl, Tree.ForStatement stmt) { class ForVisitor extends Visitor { Tree.Variable variable = null; public void visit(Tree.ValueIterator valueIterator) { assert variable == null; variable = valueIterator.getVariable(); } public void visit(Tree.KeyValueIterator keyValueIterator) { assert variable == null; // FIXME: implement this throw new RuntimeException("Not implemented: " + keyValueIterator.getNodeType()); } } ; // FIXME: implement this if (stmt.getFailClause() != null) throw new RuntimeException("Not implemented: " + stmt.getFailClause().getNodeType()); ForVisitor visitor = new ForVisitor(); stmt.getForClause().getForIterator().visit(visitor); JCExpression item_type = gen.variableType(visitor.variable.getType(), null); // ceylon.language.Iterator<T> $ceylontmpX = ITERABLE.iterator(); JCExpression containment = gen.expressionGen.convertExpression(stmt.getForClause().getForIterator().getSpecifierExpression().getExpression()); JCVariableDecl iter_decl = at(stmt).VarDef(make().Modifiers(0), names().fromString(tempName()), gen.iteratorType(item_type), at(stmt).Apply(null, at(stmt).Select(containment, names().fromString("iterator")), List.<JCExpression> nil())); List<JCStatement> outer = List.<JCStatement> of(iter_decl); JCIdent iter = at(stmt).Ident(iter_decl.getName()); // ceylon.language.Optional<T> $ceylontmpY = $ceylontmpX.head(); JCVariableDecl optional_item_decl = at(stmt).VarDef(make().Modifiers(FINAL), names().fromString(tempName()), gen.optionalType(item_type), at(stmt).Apply(null, at(stmt).Select(iter, names().fromString("head")), List.<JCExpression> nil())); List<JCStatement> while_loop = List.<JCStatement> of(optional_item_decl); JCIdent optional_item = at(stmt).Ident(optional_item_decl.getName()); // T n = $ceylontmpY.t; JCVariableDecl item_decl = at(stmt).VarDef(make().Modifiers(0), names().fromString(visitor.variable.getIdentifier().getText()), item_type, at(stmt).Apply(null, at(stmt).Select(optional_item, names().fromString("$internalErasedExists")), List.<JCExpression> nil())); List<JCStatement> inner = List.<JCStatement> of(item_decl); // The user-supplied contents of the loop inner = inner.appendList(convertStmts(cdecl, stmt.getForClause().getBlock().getStatements())); // if ($ceylontmpY != null) ... else break; JCStatement test = at(stmt).If(at(stmt).Binary(JCTree.NE, optional_item, make().Literal(TypeTags.BOT, null)), at(stmt).Block(0, inner), at(stmt).Block(0, List.<JCStatement> of(at(stmt).Break(null)))); while_loop = while_loop.append(test); // $ceylontmpX = $ceylontmpX.tail(); JCExpression next = at(stmt).Assign(iter, at(stmt).Apply(null, at(stmt).Select(iter, names().fromString("tail")), List.<JCExpression> nil())); while_loop = while_loop.append(at(stmt).Exec(next)); // while (True)... outer = outer.append(at(stmt).WhileLoop(at(stmt).Literal(TypeTags.BOOLEAN, 1), at(stmt).Block(0, while_loop))); return at(stmt).Block(0, outer); } private JCStatement convert(Tree.Return ret) { Tree.Expression expr = ret.getExpression(); JCExpression returnExpr = expr != null ? gen.expressionGen.convertExpression(expr) : null; return at(ret).Return(returnExpr); } private JCIdent convert(Tree.Identifier identifier) { return at(identifier).Ident(names().fromString(identifier.getText())); } }
true
true
private JCStatement convertCondition(Tree.Condition cond, int tag, JCBlock thenPart, JCBlock elsePart) { if (cond instanceof Tree.ExistsCondition) { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; Tree.Identifier name = exists.getVariable().getIdentifier(); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedExists")); Name tmp2 = names().fromString(name.getText()); JCExpression type; if (exists.getVariable().getType() == null) { type = makeIdent(syms().ceylonAnyType); } else { type = gen.variableType(exists.getVariable().getType(), null); } JCExpression expr; if (exists.getExpression() == null) { expr = at(cond).Ident(tmp2); } else { expr = gen.expressionGen.convertExpression(exists.getExpression()); } expr = at(cond).Apply(null, at(cond).Select(expr, names().fromString("$internalErasedExists")), List.<JCExpression> nil()); // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, type, exists.getVariable().getType() == null ? expr : null); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).Ident(tmp)); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCTree.JCBinary test = at(cond).Binary(JCTree.NE, assignment, make().Literal(TypeTags.BOT, null)); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.IsCondition) { // FIXME: This code has a lot in common with the ExistsExpression // above, but it has a niggling few things that are different. // It needs to be refactored. Tree.IsCondition isExpr = (Tree.IsCondition) cond; Tree.Identifier name = isExpr.getVariable().getIdentifier(); JCExpression type = gen.variableType(isExpr.getType(), null); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedIs")); Name tmp2 = names().fromString(name.getText()); JCExpression expr; if (isExpr.getExpression() == null) { expr = convert(name); } else { expr = gen.expressionGen.convertExpression(isExpr.getExpression()); } // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, makeIdent(syms().ceylonAnyType), expr); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).TypeCast(type, at(cond).Ident(tmp))); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCExpression test = at(cond).TypeTest(assignment, type); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; JCExpression test = gen.expressionGen.convertExpression(booleanCondition.getExpression()); test = at(cond).Binary(JCTree.EQ, test, makeIdent("ceylon", "language", "_true", "value")); JCStatement result; switch (tag) { case JCTree.IF: result = at(cond).If(test, thenPart, elsePart); break; case JCTree.WHILELOOP: assert elsePart == null; result = at(cond).WhileLoop(test, thenPart); break; default: throw new RuntimeException(); } return result; } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } }
private JCStatement convertCondition(Tree.Condition cond, int tag, JCBlock thenPart, JCBlock elsePart) { if (cond instanceof Tree.ExistsCondition) { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; Tree.Identifier name = exists.getVariable().getIdentifier(); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedExists")); Name tmp2 = names().fromString(name.getText()); JCExpression type; if (exists.getVariable().getType() == null) { type = makeIdent(syms().ceylonAnyType); } else { type = gen.variableType(exists.getVariable().getType(), null); } JCExpression expr; if (exists.getExpression() == null) { expr = at(cond).Ident(tmp2); } else { expr = gen.expressionGen.convertExpression(exists.getExpression()); } expr = at(cond).Apply(null, at(cond).Select(expr, names().fromString("$internalErasedExists")), List.<JCExpression> nil()); // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, type, exists.getVariable().getType() == null ? expr : null); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).Ident(tmp)); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCTree.JCBinary test = at(cond).Binary(JCTree.NE, assignment, make().Literal(TypeTags.BOT, null)); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.IsCondition) { // FIXME: This code has a lot in common with the ExistsExpression // above, but it has a niggling few things that are different. // It needs to be refactored. Tree.IsCondition isExpr = (Tree.IsCondition) cond; Tree.Identifier name = isExpr.getVariable().getIdentifier(); JCExpression type = gen.variableType(isExpr.getType(), null); // We're going to give this variable an initializer in order to be // able to determine its type, but the initializer will be deleted // in LowerCeylon. Do not change the string "Deleted". Name tmp = names().fromString(tempName("DeletedIs")); Name tmp2 = names().fromString(name.getText()); JCExpression expr; if (isExpr.getExpression() == null) { expr = convert(name); } else { expr = gen.expressionGen.convertExpression(isExpr.getExpression()); } // This temp variable really should be SYNTHETIC, but then javac // won't let you use it... JCVariableDecl decl = at(cond).VarDef(make().Modifiers(0), tmp, makeIdent(syms().ceylonAnyType), expr); JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), tmp2, type, at(cond).TypeCast(type, at(cond).Ident(tmp))); thenPart = at(cond).Block(0, List.<JCStatement> of(decl2, thenPart)); JCExpression assignment = at(cond).Assign(make().Ident(decl.name), expr); JCExpression test = at(cond).TypeTest(assignment, type); JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = at(cond).If(test, thenPart, elsePart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); case JCTree.WHILELOOP: assert elsePart == null; cond1 = at(cond).WhileLoop(test, thenPart); return at(cond).Block(0, List.<JCStatement> of(decl, cond1)); default: throw new RuntimeException(); } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; JCExpression test = gen.expressionGen.convertExpression(booleanCondition.getExpression()); JCExpression trueValue = at(cond).Apply(List.<JCTree.JCExpression>nil(), makeIdent("ceylon", "language", "$true", "getTrue"), List.<JCTree.JCExpression>nil()); test = at(cond).Binary(JCTree.EQ, test, trueValue); JCStatement result; switch (tag) { case JCTree.IF: result = at(cond).If(test, thenPart, elsePart); break; case JCTree.WHILELOOP: assert elsePart == null; result = at(cond).WhileLoop(test, thenPart); break; default: throw new RuntimeException(); } return result; } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } }