\";\n\n\t\ttry {\n\t\t\tDocument dom = Helper.getDocument(html);\n\t\t\tassertNotNull(dom);\n\n\t\t\tElement element = dom.getElementById(\"firstdiv\");\n\n\t\t\tEventable clickable = new Eventable(element, \"onclick\");\n\t\t\tassertNotNull(clickable);\n\n\t\t\t/*\n\t\t\t * String infoexpected = \"DIV: id=firstdiv, xpath /HTML[1]/BODY[1]/DIV[1] onclick\";\n\t\t\t */\n\t\t\tString infoexpected =\n\t\t\t \"ID: firstdivDIV: id=\\\"firstdiv\\\" onclick xpath \" + \"/HTML[1]/BODY[1]/DIV[1]\";\n\t\t\tSystem.out.println(clickable);\n\t\t\tassertEquals(infoexpected, clickable.toString());\n\t\t} catch (Exception e) {\n\t\t\tfail(e.getMessage());\n\t\t}\n\t}\n\n\t@Test\n\tpublic void testEdge() {\n\t\tStateVertix s1 = new StateVertix(\"stateSource\", \"dom1\");\n\t\tStateVertix s2 = new StateVertix(\"stateTarget\", \"dom2\");\n\n\t\tEventable e = new Eventable();\n\t\tEdge edge = new Edge(s1, s2);\n\t\te.setEdge(edge);\n\t\tassertNotNull(\"Edge not null\", edge);\n\n\t\tassertEquals(s1, e.getEdge().getFromStateVertix());\n\t\tassertEquals(s2, e.getEdge().getToStateVertix());\n\n\t}\n}\n"},"message":{"kind":"string","value":"deleted Edge. source and target states are included in Eventable class.\n"},"old_file":{"kind":"string","value":"src/test/java/com/crawljax/core/state/EventableTest.java"},"subject":{"kind":"string","value":"deleted Edge. source and target states are included in Eventable class."}}},{"rowIdx":145814,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"e9422ce69b86b35ee29b053787becc9f6016a5ea"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jembi/openxds,jembi/openxds,jembi/openxds"},"new_contents":{"kind":"string","value":"/**\r\n * Copyright (c) 2009-2010 Misys Open Source Solutions (MOSS) and others\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r\n * implied. See the License for the specific language governing\r\n * permissions and limitations under the License.\r\n *\r\n * Contributors:\r\n * Misys Open Source Solutions - initial API and implementation\r\n * -\r\n */\r\n\r\npackage org.openhealthtools.openxds.dao;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport org.apache.commons.logging.Log;\r\nimport org.apache.commons.logging.LogFactory;\r\nimport org.openhealthtools.openxds.registry.PersonIdentifier;\r\nimport org.openhealthtools.openxds.registry.api.RegistryPatientException;\r\nimport org.springframework.orm.hibernate3.support.HibernateDaoSupport;\r\n\r\n/* \r\n* @author Raja\r\n*/\r\n\r\npublic class xdsRegistryPatientDaoImpl extends HibernateDaoSupport implements XdsRegistryPatientDao{\r\n\tprivate static final Log log = LogFactory.getLog(xdsRegistryPatientDaoImpl.class);\r\n\t\r\n\tpublic PersonIdentifier getPersonById(PersonIdentifier patientId) throws RegistryPatientException{\r\n\t\treturn\tgetPersonById(patientId, false);\r\n\t}\r\n\r\n\tpublic PersonIdentifier getPersonById(PersonIdentifier patientId, boolean merged) throws RegistryPatientException{\r\n\t\tList list = new ArrayList();\r\n\t\tPersonIdentifier personIdentifier = null;\r\n\t\tString personId = patientId.getPatientId();\r\n\t\tString assigningAuthority = patientId.getAssigningAuthority();\r\n\t\tString deletePatient = \"N\";\r\n\t\tString mergedPatient = (merged) ? \"Y\" : \"N\";\r\n\t\ttry{\r\n\t\tlist = this.getHibernateTemplate().find(\r\n\t\t\t\t\"from PersonIdentifier where patientid = '\"+ personId +\"' and assigningauthority ='\" + assigningAuthority + \"' and deleted ='\" + deletePatient + \"' and merged ='\" + mergedPatient + \"'\");\r\n\t\t}catch (Exception e) {\r\n\t\t\tlog.error(\"Failed to retrieve person identifier from registry patient service\",e);\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\r\n\t\tif (list.size() > 0)\r\n\t\t\tpersonIdentifier = (PersonIdentifier) list.get(0);\r\n\t\treturn personIdentifier;\r\n\t}\r\n\t\r\n\tpublic void savePersonIdentifier(PersonIdentifier identifier) throws RegistryPatientException {\r\n\t\ttry {\r\n\t\t\t this.getHibernateTemplate().save(identifier);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\tpublic void updatePersonIdentifier(PersonIdentifier identifier) throws RegistryPatientException {\r\n\t\ttry {\r\n\t\t\t this.getHibernateTemplate().update(identifier);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"openxds/openxds-registry-patient-lightweight/src/main/java/org/openhealthtools/openxds/dao/xdsRegistryPatientDaoImpl.java"},"old_contents":{"kind":"string","value":"/**\r\n * Copyright (c) 2009-2010 Misys Open Source Solutions (MOSS) and others\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\r\n * implied. See the License for the specific language governing\r\n * permissions and limitations under the License.\r\n *\r\n * Contributors:\r\n * Misys Open Source Solutions - initial API and implementation\r\n * -\r\n */\r\n\r\npackage org.openhealthtools.openxds.dao;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport org.apache.commons.logging.Log;\r\nimport org.apache.commons.logging.LogFactory;\r\nimport org.openhealthtools.openxds.registry.PersonIdentifier;\r\nimport org.openhealthtools.openxds.registry.api.RegistryPatientException;\r\nimport org.springframework.orm.hibernate3.support.HibernateDaoSupport;\r\n\r\n/* \r\n* @author Raja\r\n*/\r\n\r\npublic class xdsRegistryPatientDaoImpl extends HibernateDaoSupport implements XdsRegistryPatientDao{\r\n\tprivate static final Log log = LogFactory.getLog(xdsRegistryPatientDaoImpl.class);\r\n\t\r\n\t@Override\r\n\tpublic PersonIdentifier getPersonById(PersonIdentifier patientId) throws RegistryPatientException{\r\n\t\treturn\tgetPersonById(patientId, false);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic PersonIdentifier getPersonById(PersonIdentifier patientId, boolean merged) throws RegistryPatientException{\r\n\t\tList list = new ArrayList();\r\n\t\tPersonIdentifier personIdentifier = null;\r\n\t\tString personId = patientId.getPatientId();\r\n\t\tString assigningAuthority = patientId.getAssigningAuthority();\r\n\t\tString deletePatient = \"N\";\r\n\t\tString mergedPatient = (merged) ? \"Y\" : \"N\";\r\n\t\ttry{\r\n\t\tlist = this.getHibernateTemplate().find(\r\n\t\t\t\t\"from PersonIdentifier where patientid = '\"+ personId +\"' and assigningauthority ='\" + assigningAuthority + \"' and deleted ='\" + deletePatient + \"' and merged ='\" + mergedPatient + \"'\");\r\n\t\t}catch (Exception e) {\r\n\t\t\tlog.error(\"Failed to retrieve person identifier from registry patient service\",e);\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\r\n\t\tif (list.size() > 0)\r\n\t\t\tpersonIdentifier = (PersonIdentifier) list.get(0);\r\n\t\treturn personIdentifier;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void savePersonIdentifier(PersonIdentifier identifier) throws RegistryPatientException {\r\n\t\ttry {\r\n\t\t\t this.getHibernateTemplate().save(identifier);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void updatePersonIdentifier(PersonIdentifier identifier) throws RegistryPatientException {\r\n\t\ttry {\r\n\t\t\t this.getHibernateTemplate().update(identifier);\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new RegistryPatientException(e);\r\n\t\t}\r\n\t\t\r\n\t}\r\n\r\n}\r\n"},"message":{"kind":"string","value":"removed @Override\n"},"old_file":{"kind":"string","value":"openxds/openxds-registry-patient-lightweight/src/main/java/org/openhealthtools/openxds/dao/xdsRegistryPatientDaoImpl.java"},"subject":{"kind":"string","value":"removed @Override"}}},{"rowIdx":145815,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"02054bb8ce8691158f1e1ce0bfb5ca87570ea7c0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"ucam-cl-dtg/urop-2014-git"},"new_contents":{"kind":"string","value":"/* vim: set et ts=4 sts=4 sw=4 tw=72 : */\n/* See the LICENSE file for the license of the project */\npackage uk.ac.cam.cl.git;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\nimport uk.ac.cam.cl.git.api.DuplicateRepoNameException;\nimport uk.ac.cam.cl.git.api.RepositoryNotFoundException;\nimport uk.ac.cam.cl.git.configuration.ConfigurationLoader;\n\nimport com.jcraft.jsch.*;\n\n/**\n * @author Isaac Dunn <ird28@cam.ac.uk>\n * @author Kovacsics Robert <rmk35@cam.ac.uk>\n * @version 0.1\n */\npublic class ConfigDatabase {\n /* For logging */\n private static final Logger log = LoggerFactory.getLogger(ConfigDatabase.class);\n \n private static final String[] environmentVariables = new String[]\n {\"HOME=\" + ConfigurationLoader.getConfig().getGitoliteHome()\n , \"PATH=\" + ConfigurationLoader.getConfig().getGitolitePath()\n , \"GL_LIBDIR=\" + ConfigurationLoader.getConfig().getGitoliteLibdir()};\n\n @Inject private RepositoryCollection reposCollection;\n \n private static final Injector injector = Guice.createInjector(new DatabaseModule());\n \n private static final ConfigDatabase instance = injector.getInstance(ConfigDatabase.class);\n \n public static ConfigDatabase instance() {\n return instance;\n }\n\n /**\n * For unit testing only, to allow a mock collection to be used.\n * Replaces the repository collection with the argument.\n * @param reposCollection The collection to be used.\n */\n //@Inject\n void setReposCollection(RepositoryCollection rCollection) {\n reposCollection = rCollection;\n }\n\n /**\n * Returns a list of all the repository objects in the collection\n *\n * @return List of repository objects in the collection\n */\n public List getRepos()\n { /* TODO: Test ordered-ness or repositories. */\n return reposCollection.listRepos();\n \n }\n \n \n /**\n * Returns the repository object with the given name in the\n * database.\n * \n * @param name The name of the repository\n * @return The requested repository object\n * @throws RepositoryNotFoundException \n */\n public Repository getRepoByName(String name) throws RepositoryNotFoundException {\n return reposCollection.getRepo(name);\n }\n\n /**\n * Removes the repository object with the given name from the\n * database if present in the database.\n * \n * @param name The name of the repository to remove\n * @throws IOException\n * @throws RepositoryNotFoundException\n */\n public void delRepoByName(String repoName) throws IOException, RepositoryNotFoundException {\n log.info(\"Deleting repository \\\"\" + repoName + \"\\\"\");\n if (!reposCollection.contains(repoName))\n throw new RepositoryNotFoundException();\n reposCollection.removeRepo(repoName);\n generateConfigFile();\n log.info(\"Deleted repository \\\"\" + repoName + \"\\\"\");\n }\n \n /**\n * Removes all repositories from the collection.\n * For unit testing only.\n */\n void deleteAll() throws IOException {\n reposCollection.removeAll();\n generateConfigFile();\n }\n\n /**\n * Generates config file for gitolite and writes it to gitoliteGeneratedConfigFile (see ConfigurationLoader).\n *
\n * Accesses the database to find repositories and assumes the\n * Repository.toString() method returns the appropriate representation. The\n * main conf file should have an include statement so that\n * when the hook is called, the updates are made. The hook is\n * called at the end of this method.\n *\n * @throws IOException Typically an unrecoverable problem.\n */\n public void generateConfigFile() throws IOException {\n log.info(\"Generating config file \\\"\" +\n ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile()\n + \"\\\"\");\n StringBuilder output = new StringBuilder();\n\n for (Repository r : getRepos())\n output.append(r.toString() + \"\\n\");\n\n /* Write out file */\n File configFile = new File(ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile());\n BufferedWriter buffWriter = new BufferedWriter(new FileWriter(configFile, false));\n buffWriter.write(output.toString());\n buffWriter.flush();\n buffWriter.close();\n runGitoliteUpdate(new String[] {\"compile\",\n /* Workaround first compile not updating file, only\n * doing git init --bare */ \"compile\",\n \"trigger POST_COMPILE\"});\n log.info(\"Generated config file \\\"\" +\n ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile()\n + \"\\\"\");\n }\n\n /**\n * Adds a new repository to the mongo database for inclusion in the\n * conf file when generated.\n *\n * @param repo The repository to be added\n * @throws DuplicateRepoNameException A repository with this name already\n * exists.\n */\n public void addRepo(Repository repo) throws DuplicateRepoNameException, IOException {\n reposCollection.insertRepo(repo);\n generateConfigFile();\n }\n\n /**\n * Takes public key and username as strings, writes the key to\n * getGitoliteSSHKeyLocation (see ConfigurationLoader), and calls the hook.\n *\n * @param key The SSH key to be added\n * @param username The name of the user to be added\n * @throws IOException \n */\n public void addSSHKey(String key, String userName) throws IOException {\n log.info(\"Adding key for \\\"\" + userName + \"\\\" to \\\"\"\n + ConfigurationLoader.getConfig()\n .getGitoliteSSHKeyLocation() + \"\\\"\");\n File keyFile = new File(ConfigurationLoader.getConfig()\n .getGitoliteSSHKeyLocation() + \"/\" + userName + \".pub\");\n if (!keyFile.exists()) {\n if (keyFile.getParentFile() != null)\n keyFile.getParentFile().mkdirs(); /* Make parent directories if necessary */\n keyFile.createNewFile();\n }\n BufferedWriter buffWriter = new BufferedWriter(new FileWriter(keyFile));\n buffWriter.write(key);\n buffWriter.close();\n runGitoliteUpdate(new String[] {\"trigger SSH_AUTHKEYS\"});\n log.info(\"Finished adding key for \\\"\" + userName + \"\\\"\");\n }\n\n /**\n * Updates the given repository.\n *\n * This selects the repository uniquely using the ID (not\n * technically the name of the repository, but is equivalent).\n *\n * @param repo The updated repository (there must also be a\n * repository by this name).\n * @throws RepositoryNotFoundException \n * @throws MongoException If the update operation fails (for some\n * unknown reason).\n */\n public void updateRepo(Repository repo) throws IOException, RepositoryNotFoundException\n {\n reposCollection.updateRepo(repo);\n generateConfigFile();\n }\n\n /**\n * Runs the gitolite update programs.\n *
\n * This is because gitolite is a perl program and compiles the\n * configuration file into a perl module, which it uses.\n * This just forces recompilation.\n *\n * @param updates List of things to recompile/reconfigure.\n */\n void runGitoliteUpdate(String[] updates) throws IOException\n {\n log.info(\"Starting gitolite recompilation\");\n for (String command : updates)\n {\n try\n {\n JSch ssh = new JSch();\n ssh.setKnownHosts(\"~/.ssh/known_hosts\");\n ssh.addIdentity(\"~/.ssh/id_rsa\");\n Session session = ssh.getSession(ConfigurationLoader\n .getConfig().getRepoUser()\n , \"localhost\"\n , 22);\n session.connect();\n\n ChannelExec channel = (ChannelExec)session.openChannel(\"exec\");\n channel.setCommand(command);\n\n channel.setInputStream(null);\n /* Gitolite does native logging */\n channel.setOutputStream(null);\n channel.setErrStream(null);\n\n channel.connect();\n\n while (channel.isClosed())\n {\n try\n {\n Thread.sleep(100);\n }\n catch (InterruptedException e)\n {\n /* If we woke up earlier from sleep than\n * expected, continue to check for channel\n * status.\n */\n }\n }\n channel.disconnect();\n session.disconnect();\n }\n catch (JSchException e)\n {\n throw new IOException(e);\n }\n }\n log.info(\"Finished gitolite recompilation\");\n }\n \n /**\n * This rebuilds the MongoDB database using the gitolite\n * configuration file, in case the two become out of sync.\n */\n private void rebuildDatabaseFromGitolite() throws IOException, DuplicateRepoNameException {\n reposCollection.removeAll(); // Empty database collection\n BufferedReader reader = new BufferedReader(new FileReader(new File(\n ConfigurationLoader.getConfig().getGitoliteGeneratedConfigFile())));\n String firstLine;\n while ((firstLine = reader.readLine()) != null) { // While not end of file\n String repoName = firstLine.split(\"\\\\s\\\\+\")[1]; // Repo name is second word of first line\n \n String[] readWriteLine = reader.readLine().split(\"=\")[1].trim().split(\"\\\\s\\\\+\");\n // We want the words to the right of the \"RW =\"\n \n String nextLine = reader.readLine();\n String[] readOnlyLine;\n String[] auxiliaryLine;\n if (nextLine.startsWith(\"#\")) { // No users with read only access\n readOnlyLine = new String[0];\n auxiliaryLine = nextLine.split(\" \");\n }\n else { // At least one user with read only access\n readOnlyLine = nextLine.split(\"=\")[1].trim().split(\"\\\\s\\\\+\");\n auxiliaryLine = reader.readLine().split(\"\\\\s\\\\+\");\n }\n \n String owner = readWriteLine[0]; // Owner is always first RW entry - see Repository.toString()\n List readWrites = new LinkedList(Arrays.asList(readWriteLine));\n readWrites.remove(0); // remove owner from RW list as owner is automatically added\n List readOnlys = Arrays.asList(readOnlyLine);\n String parent = auxiliaryLine[1]; // see Repository.toString()\n String parent_hidden = auxiliaryLine[2];\n Repository toInsert = new Repository(repoName, owner, readWrites,\n readOnlys, parent, parent_hidden, null);\n reposCollection.insertRepo(toInsert);\n reader.readLine(); // extra line between repos\n }\n reader.close();\n }\n\n}\n"},"new_file":{"kind":"string","value":"server/src/main/java/uk/ac/cam/cl/git/ConfigDatabase.java"},"old_contents":{"kind":"string","value":"/* vim: set et ts=4 sts=4 sw=4 tw=72 : */\n/* See the LICENSE file for the license of the project */\npackage uk.ac.cam.cl.git;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\nimport uk.ac.cam.cl.git.api.DuplicateRepoNameException;\nimport uk.ac.cam.cl.git.api.RepositoryNotFoundException;\nimport uk.ac.cam.cl.git.configuration.ConfigurationLoader;\n\nimport com.jcraft.jsch.*;\n\n/**\n * @author Isaac Dunn <ird28@cam.ac.uk>\n * @author Kovacsics Robert <rmk35@cam.ac.uk>\n * @version 0.1\n */\npublic class ConfigDatabase {\n /* For logging */\n private static final Logger log = LoggerFactory.getLogger(ConfigDatabase.class);\n \n private static final String[] environmentVariables = new String[]\n {\"HOME=\" + ConfigurationLoader.getConfig().getGitoliteHome()\n , \"PATH=\" + ConfigurationLoader.getConfig().getGitolitePath()\n , \"GL_LIBDIR=\" + ConfigurationLoader.getConfig().getGitoliteLibdir()};\n\n @Inject private RepositoryCollection reposCollection;\n \n private static final Injector injector = Guice.createInjector(new DatabaseModule());\n \n private static final ConfigDatabase instance = injector.getInstance(ConfigDatabase.class);\n \n public static ConfigDatabase instance() {\n return instance;\n }\n\n /**\n * For unit testing only, to allow a mock collection to be used.\n * Replaces the repository collection with the argument.\n * @param reposCollection The collection to be used.\n */\n //@Inject\n void setReposCollection(RepositoryCollection rCollection) {\n reposCollection = rCollection;\n }\n\n /**\n * Returns a list of all the repository objects in the collection\n *\n * @return List of repository objects in the collection\n */\n public List getRepos()\n { /* TODO: Test ordered-ness or repositories. */\n return reposCollection.listRepos();\n \n }\n \n \n /**\n * Returns the repository object with the given name in the\n * database.\n * \n * @param name The name of the repository\n * @return The requested repository object\n * @throws RepositoryNotFoundException \n */\n public Repository getRepoByName(String name) throws RepositoryNotFoundException {\n return reposCollection.getRepo(name);\n }\n\n /**\n * Removes the repository object with the given name from the\n * database if present in the database.\n * \n * @param name The name of the repository to remove\n * @throws IOException\n * @throws RepositoryNotFoundException\n */\n public void delRepoByName(String repoName) throws IOException, RepositoryNotFoundException {\n log.info(\"Deleting repository \\\"\" + repoName + \"\\\"\");\n if (!reposCollection.contains(repoName))\n throw new RepositoryNotFoundException();\n reposCollection.removeRepo(repoName);\n generateConfigFile();\n log.info(\"Deleted repository \\\"\" + repoName + \"\\\"\");\n }\n \n /**\n * Removes all repositories from the collection.\n * For unit testing only.\n */\n void deleteAll() throws IOException {\n reposCollection.removeAll();\n generateConfigFile();\n }\n\n /**\n * Generates config file for gitolite and writes it to gitoliteGeneratedConfigFile (see ConfigurationLoader).\n *
\n * Accesses the database to find repositories and assumes the\n * Repository.toString() method returns the appropriate representation. The\n * main conf file should have an include statement so that\n * when the hook is called, the updates are made. The hook is\n * called at the end of this method.\n *\n * @throws IOException Typically an unrecoverable problem.\n */\n public void generateConfigFile() throws IOException {\n log.info(\"Generating config file \\\"\" +\n ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile()\n + \"\\\"\");\n StringBuilder output = new StringBuilder();\n\n for (Repository r : getRepos())\n output.append(r.toString() + \"\\n\");\n\n /* Write out file */\n File configFile = new File(ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile());\n BufferedWriter buffWriter = new BufferedWriter(new FileWriter(configFile, false));\n buffWriter.write(output.toString());\n buffWriter.flush();\n buffWriter.close();\n runGitoliteUpdate(new String[] {\"compile\",\n \"trigger POST_COMPILE\"});\n log.info(\"Generated config file \\\"\" +\n ConfigurationLoader.getConfig()\n .getGitoliteGeneratedConfigFile()\n + \"\\\"\");\n }\n\n /**\n * Adds a new repository to the mongo database for inclusion in the\n * conf file when generated.\n *\n * @param repo The repository to be added\n * @throws DuplicateRepoNameException A repository with this name already\n * exists.\n */\n public void addRepo(Repository repo) throws DuplicateRepoNameException, IOException {\n reposCollection.insertRepo(repo);\n generateConfigFile();\n }\n\n /**\n * Takes public key and username as strings, writes the key to\n * getGitoliteSSHKeyLocation (see ConfigurationLoader), and calls the hook.\n *\n * @param key The SSH key to be added\n * @param username The name of the user to be added\n * @throws IOException \n */\n public void addSSHKey(String key, String userName) throws IOException {\n log.info(\"Adding key for \\\"\" + userName + \"\\\" to \\\"\"\n + ConfigurationLoader.getConfig()\n .getGitoliteSSHKeyLocation() + \"\\\"\");\n File keyFile = new File(ConfigurationLoader.getConfig()\n .getGitoliteSSHKeyLocation() + \"/\" + userName + \".pub\");\n if (!keyFile.exists()) {\n if (keyFile.getParentFile() != null)\n keyFile.getParentFile().mkdirs(); /* Make parent directories if necessary */\n keyFile.createNewFile();\n }\n BufferedWriter buffWriter = new BufferedWriter(new FileWriter(keyFile));\n buffWriter.write(key);\n buffWriter.close();\n runGitoliteUpdate(new String[] {\"trigger SSH_AUTHKEYS\"});\n log.info(\"Finished adding key for \\\"\" + userName + \"\\\"\");\n }\n\n /**\n * Updates the given repository.\n *\n * This selects the repository uniquely using the ID (not\n * technically the name of the repository, but is equivalent).\n *\n * @param repo The updated repository (there must also be a\n * repository by this name).\n * @throws RepositoryNotFoundException \n * @throws MongoException If the update operation fails (for some\n * unknown reason).\n */\n public void updateRepo(Repository repo) throws IOException, RepositoryNotFoundException\n {\n reposCollection.updateRepo(repo);\n generateConfigFile();\n }\n\n /**\n * Runs the gitolite update programs.\n *
\n * This is because gitolite is a perl program and compiles the\n * configuration file into a perl module, which it uses.\n * This just forces recompilation.\n *\n * @param updates List of things to recompile/reconfigure.\n */\n void runGitoliteUpdate(String[] updates) throws IOException\n {\n log.info(\"Starting gitolite recompilation\");\n for (String command : updates)\n {\n try\n {\n JSch ssh = new JSch();\n ssh.setKnownHosts(\"~/.ssh/known_hosts\");\n ssh.addIdentity(\"~/.ssh/id_rsa\");\n Session session = ssh.getSession(ConfigurationLoader\n .getConfig().getRepoUser()\n , \"localhost\"\n , 22);\n session.connect();\n\n ChannelExec channel = (ChannelExec)session.openChannel(\"exec\");\n channel.setCommand(command);\n\n channel.setInputStream(null);\n /* Gitolite does native logging */\n channel.setOutputStream(null);\n channel.setErrStream(null);\n\n channel.connect();\n\n while (channel.isClosed())\n {\n try\n {\n Thread.sleep(100);\n }\n catch (InterruptedException e)\n {\n /* If we woke up earlier from sleep than\n * expected, continue to check for channel\n * status.\n */\n }\n }\n channel.disconnect();\n session.disconnect();\n }\n catch (JSchException e)\n {\n throw new IOException(e);\n }\n }\n log.info(\"Finished gitolite recompilation\");\n }\n \n /**\n * This rebuilds the MongoDB database using the gitolite\n * configuration file, in case the two become out of sync.\n */\n private void rebuildDatabaseFromGitolite() throws IOException, DuplicateRepoNameException {\n reposCollection.removeAll(); // Empty database collection\n BufferedReader reader = new BufferedReader(new FileReader(new File(\n ConfigurationLoader.getConfig().getGitoliteGeneratedConfigFile())));\n String firstLine;\n while ((firstLine = reader.readLine()) != null) { // While not end of file\n String repoName = firstLine.split(\"\\\\s\\\\+\")[1]; // Repo name is second word of first line\n \n String[] readWriteLine = reader.readLine().split(\"=\")[1].trim().split(\"\\\\s\\\\+\");\n // We want the words to the right of the \"RW =\"\n \n String nextLine = reader.readLine();\n String[] readOnlyLine;\n String[] auxiliaryLine;\n if (nextLine.startsWith(\"#\")) { // No users with read only access\n readOnlyLine = new String[0];\n auxiliaryLine = nextLine.split(\" \");\n }\n else { // At least one user with read only access\n readOnlyLine = nextLine.split(\"=\")[1].trim().split(\"\\\\s\\\\+\");\n auxiliaryLine = reader.readLine().split(\"\\\\s\\\\+\");\n }\n \n String owner = readWriteLine[0]; // Owner is always first RW entry - see Repository.toString()\n List readWrites = new LinkedList(Arrays.asList(readWriteLine));\n readWrites.remove(0); // remove owner from RW list as owner is automatically added\n List readOnlys = Arrays.asList(readOnlyLine);\n String parent = auxiliaryLine[1]; // see Repository.toString()\n String parent_hidden = auxiliaryLine[2];\n Repository toInsert = new Repository(repoName, owner, readWrites,\n readOnlys, parent, parent_hidden, null);\n reposCollection.insertRepo(toInsert);\n reader.readLine(); // extra line between repos\n }\n reader.close();\n }\n\n}\n"},"message":{"kind":"string","value":"Added workaround to compile only doing git init\n"},"old_file":{"kind":"string","value":"server/src/main/java/uk/ac/cam/cl/git/ConfigDatabase.java"},"subject":{"kind":"string","value":"Added workaround to compile only doing git init"}}},{"rowIdx":145816,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"ba4e7f555f19ffd410ff12859f53dba2e7c48915"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"sarnowski/eve-interfaces"},"new_contents":{"kind":"string","value":"/**\n * Copyright 2010 Tobias Sarnowski\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.eveonline.api.map;\n\nimport com.eveonline.api.ApiService;\nimport com.eveonline.api.exceptions.ApiException;\n\n/**\n * @author Tobias Sarnowski\n */\npublic interface FacWarSystemsApi extends ApiService {\n\n public static final String XMLPATH = \"/map/FacWarSystems.xml.aspx\";\n\n\n\t/**\n\t * @return list of solar systems used for the faction warfare\n\t * @throws ApiException\n\t */\n\tFacWarSystems getFactionWarfareSystems() throws ApiException;\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/eveonline/api/map/FacWarSystemsApi.java"},"old_contents":{"kind":"string","value":"/**\r\n * Copyright 2010 Tobias Sarnowski\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.eveonline.api.map;\r\n\r\nimport com.eveonline.api.ApiService;\r\nimport com.eveonline.api.exceptions.ApiException;\r\n\r\n/**\r\n * @author Tobias Sarnowski\r\n */\r\npublic interface FacWarSystemsApi extends ApiService {\r\n\r\n\t/**\r\n\t * @return list of solar systems used for the faction warfare\r\n\t * @throws ApiException\r\n\t */\r\n\tFacWarSystems getFactionWarfareSystems() throws ApiException;\r\n\r\n}\r\n"},"message":{"kind":"string","value":"added XMLPATH to FacWarSystemsApi\n"},"old_file":{"kind":"string","value":"src/main/java/com/eveonline/api/map/FacWarSystemsApi.java"},"subject":{"kind":"string","value":"added XMLPATH to FacWarSystemsApi"}}},{"rowIdx":145817,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"91823b8d2816d1932945a507ce8708c08c2cf66c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"RaviKumar7443/JPETSTORE,RaviKumar7443/JPETSTORE,RaviKumar7443/JPETSTORE"},"new_contents":{"kind":"string","value":"package org.mybatis.jpetstore.domain;\n\nimport java.io.Serializable;\nimport java.math.BigDecimal;\n\npublic class Calculate implements Serializable {\n\npublic void hello()\n{\nSystem.out.println(\"JPET Store Application\");\nSystem.out.println(\"Class name: Calculate.java\");\nSystem.out.println(\"Hello World\");\nSystem.out.println(\"Making a new Entry at Mon Dec 12 11:00:16 UTC 2016\");\nSystem.out.println(\"Mon Dec 12 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Sat Dec 10 11:00:16 UTC 2016\");\nSystem.out.println(\"Sat Dec 10 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Thu Dec 8 11:00:16 UTC 2016\");\nSystem.out.println(\"Thu Dec 8 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Tue Dec 6 11:00:16 UTC 2016\");\nSystem.out.println(\"Tue Dec 6 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Fri Dec 2 12:52:58 UTC 2016\");\nSystem.out.println(\"Fri Dec 2 12:52:58 UTC 2016\");\n}\n\n}\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 09:45:31 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 09:55:14 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 11:34:52 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 11:35:25 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 12:32:47 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:39:41 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:41:08 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:41:14 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 06:05:33 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Wed Dec 7 05:08:34 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Wed Dec 7 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 9 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Sun Dec 11 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n"},"new_file":{"kind":"string","value":"src/main/java/org/mybatis/jpetstore/domain/Calculate.java"},"old_contents":{"kind":"string","value":"package org.mybatis.jpetstore.domain;\n\nimport java.io.Serializable;\nimport java.math.BigDecimal;\n\npublic class Calculate implements Serializable {\n\npublic void hello()\n{\nSystem.out.println(\"JPET Store Application\");\nSystem.out.println(\"Class name: Calculate.java\");\nSystem.out.println(\"Hello World\");\nSystem.out.println(\"Making a new Entry at Sat Dec 10 11:00:16 UTC 2016\");\nSystem.out.println(\"Sat Dec 10 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Thu Dec 8 11:00:16 UTC 2016\");\nSystem.out.println(\"Thu Dec 8 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Tue Dec 6 11:00:16 UTC 2016\");\nSystem.out.println(\"Tue Dec 6 11:00:16 UTC 2016\");\nSystem.out.println(\"Making a new Entry at Fri Dec 2 12:52:58 UTC 2016\");\nSystem.out.println(\"Fri Dec 2 12:52:58 UTC 2016\");\n}\n\n}\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 09:45:31 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 09:55:14 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 11:34:52 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 11:35:25 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 2 12:32:47 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:39:41 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:41:08 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 05:41:14 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 06:05:33 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Mon Dec 5 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Wed Dec 7 05:08:34 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Wed Dec 7 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Fri Dec 9 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n//----------------------------------------------------\n//Comment added on date:Sun Dec 11 11:00:16 UTC 2016\n//Author: Andrew Woods, Apoorva Rao\n//Description: Adding coments for documentation\n//Project: JpetStore\n//Tools used: Jenkins, SonarQube, Rundeck\n//----------------------------------------------------\n"},"message":{"kind":"string","value":"Mon Dec 12 11:00:16 UTC 2016\n"},"old_file":{"kind":"string","value":"src/main/java/org/mybatis/jpetstore/domain/Calculate.java"},"subject":{"kind":"string","value":"Mon Dec 12 11:00:16 UTC 2016"}}},{"rowIdx":145818,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1e8a76f04884108e9d070130a7b20714cbc9fc7d"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"KernelHaven/KernelHaven,KernelHaven/KernelHaven"},"new_contents":{"kind":"string","value":"/*\n * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.ssehub.kernel_haven.analysis;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport net.ssehub.kernel_haven.SetUpException;\nimport net.ssehub.kernel_haven.build_model.BuildModel;\nimport net.ssehub.kernel_haven.code_model.SourceFile;\nimport net.ssehub.kernel_haven.config.Configuration;\nimport net.ssehub.kernel_haven.config.DefaultSettings;\nimport net.ssehub.kernel_haven.provider.AbstractProvider;\nimport net.ssehub.kernel_haven.util.ExtractorException;\nimport net.ssehub.kernel_haven.util.Timestamp;\nimport net.ssehub.kernel_haven.util.io.ITableCollection;\nimport net.ssehub.kernel_haven.util.io.ITableWriter;\nimport net.ssehub.kernel_haven.util.io.TableCollectionWriterFactory;\nimport net.ssehub.kernel_haven.util.io.csv.CsvFileCollection;\nimport net.ssehub.kernel_haven.util.null_checks.NonNull;\nimport net.ssehub.kernel_haven.variability_model.VariabilityModel;\n\n/**\n * An analysis that is a pipeline consisting of {@link AnalysisComponent}s.\n * \n * @author Adam\n */\npublic abstract class PipelineAnalysis extends AbstractAnalysis {\n\n private static PipelineAnalysis instance;\n \n private ITableCollection resultCollection;\n \n private ExtractorDataDuplicator vmStarter;\n \n private ExtractorDataDuplicator bmStarter;\n \n private ExtractorDataDuplicator> cmStarter;\n \n /**\n * Creates a new {@link PipelineAnalysis}.\n * \n * @param config The global configuration.\n */\n public PipelineAnalysis(@NonNull Configuration config) {\n super(config);\n }\n \n /**\n * The {@link PipelineAnalysis} that is the current main analysis in this execution. May be null if no\n * {@link PipelineAnalysis} is the main analysis component.\n *\n * @return The current {@link PipelineAnalysis} instance.\n */\n static PipelineAnalysis getInstance() {\n return instance;\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the variability model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the variability model.\n */\n protected @NonNull AnalysisComponent getVmComponent() {\n return vmStarter.createNewStartingComponent(config);\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the build model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the build model.\n */\n protected @NonNull AnalysisComponent getBmComponent() {\n return bmStarter.createNewStartingComponent(config);\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the code model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the code model.\n */\n protected @NonNull AnalysisComponent> getCmComponent() {\n return cmStarter.createNewStartingComponent(config);\n }\n \n /**\n * The collection that {@link AnalysisComponent}s should write their intermediate output to.\n * \n * @return The {@link ITableCollection} to write output to.\n */\n ITableCollection getResultCollection() {\n return resultCollection;\n }\n \n /**\n * Creates the result collection from the user settings.\n * \n * @return The result collection to store files in.\n * \n * @throws SetUpException If creating the result collection fails.\n */\n private ITableCollection createResultCollection() throws SetUpException {\n String outputSuffix = config.getValue(DefaultSettings.ANALYSIS_RESULT);\n File outputFile = new File(getOutputDir(), Timestamp.INSTANCE.getFilename(\n config.getValue(DefaultSettings.ANALYSIS_RESULT_NAME), outputSuffix));\n \n try {\n return TableCollectionWriterFactory.INSTANCE.createCollection(outputFile);\n } catch (IOException e) {\n throw new SetUpException(\"Can't create output for suffix \" + outputSuffix, e);\n }\n }\n \n /**\n * Creates the pipeline.\n * \n * @return The \"main\" (i.e. the last) component of the pipeline.\n * \n * @throws SetUpException If setting up the pipeline fails.\n */\n protected abstract @NonNull AnalysisComponent> createPipeline() throws SetUpException;\n\n @Override\n public void run() {\n Thread.currentThread().setName(\"AnalysisPipelineController\");\n try {\n vmStarter = new ExtractorDataDuplicator<>(vmProvider, false, \"VM\");\n bmStarter = new ExtractorDataDuplicator<>(bmProvider, false, \"BM\");\n cmStarter = new ExtractorDataDuplicator<>(cmProvider, true, \"CM\");\n \n try {\n resultCollection = createResultCollection();\n } catch (SetUpException e) {\n LOGGER.logException(\"Couldn't create output collection based on user configuration; \"\n + \"falling back to CSV\", e);\n \n resultCollection = new CsvFileCollection(new File(getOutputDir(), \n \"Analysis_\" + Timestamp.INSTANCE.getFileTimestamp()));\n }\n \n instance = this;\n \n AnalysisComponent> mainComponent = createPipeline();\n \n if (config.getValue(DefaultSettings.ANALYSIS_PIPELINE_START_EXTRACTORS)) {\n // start all extractors; this is needed here because the analysis components will most likely poll them\n // in order, which means that the extractors would not run in parallel\n vmStarter.start();\n bmStarter.start();\n cmStarter.start();\n }\n \n if (mainComponent instanceof JoinComponent) {\n joinSplitComponentFull((JoinComponent) mainComponent);\n \n } else {\n pollAndWriteOutput(mainComponent);\n }\n \n LOGGER.logDebug(\"Analysis components done\");\n \n try {\n LOGGER.logDebug(\"Closing result collection\");\n resultCollection.close();\n \n for (File file : resultCollection.getFiles()) {\n addOutputFile(file);\n }\n } catch (IOException e) {\n LOGGER.logException(\"Exception while closing output file\", e);\n }\n \n } catch (SetUpException e) {\n LOGGER.logException(\"Exception while setting up\", e);\n }\n }\n\n /**\n * Part of {@link #run()} to handle {@link JoinComponent}s. This method joins all components in parallel.\n * \n * @param mainComponent The analysis, which is joining results of multiple other components.\n */\n private void joinSplitComponentFull(@NonNull JoinComponent mainComponent) {\n List threads = new ArrayList<>(mainComponent.getInputs().length);\n \n for (AnalysisComponent> component : mainComponent.getInputs()) {\n Thread th = new Thread(() -> {\n pollAndWriteOutput(component);\n }, \"AnalysisPipelineControllerOutputThread\");\n threads.add(th);\n th.setDaemon(true);\n th.start();\n }\n \n for (Thread th : threads) {\n try {\n th.join();\n } catch (InterruptedException e) {\n }\n }\n }\n \n /**\n * Polls all output from the given component and writes it to the output file.\n * \n * @param component The component to read the output from.\n */\n private void pollAndWriteOutput(@NonNull AnalysisComponent> component) {\n LOGGER.logDebug2(\"Starting and polling output of analysis component (\", component.getClass().getSimpleName(),\n \")...\");\n \n try (ITableWriter writer = resultCollection.getWriter(component.getResultName())) {\n Object result;\n while ((result = component.getNextResult()) != null) {\n LOGGER.logDebug2(\"Got analysis result: \", result.toString());\n \n writer.writeObject(result);\n }\n } catch (IOException e) {\n LOGGER.logException(\"Exception while writing output file\", e);\n }\n }\n \n /**\n * A class for duplicating the extractor data. This way, multiple analysis components can have the same models\n * as their input data.\n * \n * @param The type of model to duplicate.\n */\n private static class ExtractorDataDuplicator implements Runnable {\n \n private @NonNull AbstractProvider provider;\n \n private boolean multiple;\n \n private @NonNull List<@NonNull StartingComponent> startingComponents;\n \n private boolean started;\n \n private @NonNull String type;\n \n /**\n * Creates a new ExtractorDataDuplicator.\n * \n * @param provider The provider to get the data from.\n * @param multiple Whether the provider should be polled multiple times or just once.\n * @param type The type of duplicator component (\"CM\", \"BM\" or \"VM\").\n */\n public ExtractorDataDuplicator(@NonNull AbstractProvider provider, boolean multiple, @NonNull String type) {\n this.provider = provider;\n this.multiple = multiple;\n this.type = type;\n startingComponents = new LinkedList<>();\n }\n \n /**\n * Creates a new starting component that will get its own copy of the data from us.\n * \n * @param config The configuration to create the component with.\n * \n * @return The starting component that can be used as input data for other analysis components.\n */\n public @NonNull StartingComponent createNewStartingComponent(@NonNull Configuration config) {\n \n StartingComponent component = new StartingComponent<>(config, this, type);\n startingComponents.add(component);\n return component;\n }\n \n /**\n * Adds the given data element to all starting components.\n * \n * @param data The data to add.\n */\n private void addToAllComponents(@NonNull T data) {\n for (StartingComponent component : startingComponents) {\n component.addResult(data);\n }\n }\n \n /**\n * Starts a new thread that copies the extractor data to all stating components created up until now.\n * This method ensures that this thread is only started once, no matter how often this method is called.\n */\n public void start() {\n synchronized (this) {\n if (!started) {\n new Thread(this, \"ExtractorDataDuplicator\").start();\n started = true;\n }\n }\n }\n \n @Override\n public void run() {\n if (multiple) {\n int numData = 0;\n int numExceptions = 0;\n \n T data;\n while ((data = provider.getNextResult()) != null) {\n addToAllComponents(data);\n numData++;\n }\n \n ExtractorException exc;\n while ((exc = provider.getNextException()) != null) {\n LOGGER.logExceptionDebug(\"Got \" + type + \"-Extractor exception\", exc);\n numExceptions++;\n }\n \n if (numData == 0) {\n // log an error when no elements could be produced\n LOGGER.logError(type + \"-Extractor: Got \" + numData + \" elements and \" + numExceptions\n + \" exceptions\");\n } else if (numExceptions > 0) {\n // log a warning when some elements got through, but others failed\n LOGGER.logWarning(type + \"-Extractor: Got \" + numData + \" elements and \" + numExceptions\n + \" exceptions\");\n }\n \n } else {\n T data = provider.getResult();\n if (data != null) {\n addToAllComponents(data);\n }\n \n ExtractorException exc = provider.getException();\n if (exc != null) {\n LOGGER.logException(\"Got \" + type + \"-Extractor exception\", exc);\n }\n }\n \n for (StartingComponent component : startingComponents) {\n synchronized (component) {\n component.done = true;\n component.notifyAll();\n }\n }\n }\n \n }\n \n /**\n * A starting component for the analysis pipeline. This is used to pass the extractor data to the analysis\n * components. This class does nothing; it is only used by {@link ExtractorDataDuplicator}.\n * \n * @param The type of result data that this produces.\n */\n private static class StartingComponent extends AnalysisComponent {\n\n private boolean done = false;\n \n private @NonNull ExtractorDataDuplicator duplicator;\n \n private @NonNull String name;\n \n /**\n * Creates a new starting component.\n * \n * @param config The global configuration.\n * @param duplicator The {@link ExtractorDataDuplicator} to start when this component is started\n * (start on demand).\n * @param type The type of starting component (\"CM\", \"BM\" or \"VM\").\n */\n public StartingComponent(@NonNull Configuration config, @NonNull ExtractorDataDuplicator duplicator,\n @NonNull String type) {\n super(config);\n this.duplicator = duplicator;\n this.name = type + \" StartingComponent\";\n }\n\n @Override\n protected void execute() {\n duplicator.start();\n \n // wait until the duplicator tells us that we are done\n synchronized (this) {\n while (!done) {\n try {\n wait();\n } catch (InterruptedException e) {\n }\n }\n }\n }\n\n @Override\n public String getResultName() {\n return name;\n }\n \n @Override\n boolean isInternalHelperComponent() {\n return true;\n }\n \n }\n\n}\n"},"new_file":{"kind":"string","value":"src/net/ssehub/kernel_haven/analysis/PipelineAnalysis.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.ssehub.kernel_haven.analysis;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport net.ssehub.kernel_haven.SetUpException;\nimport net.ssehub.kernel_haven.build_model.BuildModel;\nimport net.ssehub.kernel_haven.code_model.SourceFile;\nimport net.ssehub.kernel_haven.config.Configuration;\nimport net.ssehub.kernel_haven.config.DefaultSettings;\nimport net.ssehub.kernel_haven.provider.AbstractProvider;\nimport net.ssehub.kernel_haven.util.ExtractorException;\nimport net.ssehub.kernel_haven.util.Timestamp;\nimport net.ssehub.kernel_haven.util.io.ITableCollection;\nimport net.ssehub.kernel_haven.util.io.ITableWriter;\nimport net.ssehub.kernel_haven.util.io.TableCollectionWriterFactory;\nimport net.ssehub.kernel_haven.util.io.csv.CsvFileCollection;\nimport net.ssehub.kernel_haven.util.null_checks.NonNull;\nimport net.ssehub.kernel_haven.variability_model.VariabilityModel;\n\n/**\n * An analysis that is a pipeline consisting of {@link AnalysisComponent}s.\n * \n * @author Adam\n */\npublic abstract class PipelineAnalysis extends AbstractAnalysis {\n\n private static PipelineAnalysis instance;\n \n private ITableCollection resultCollection;\n \n private ExtractorDataDuplicator vmStarter;\n \n private ExtractorDataDuplicator bmStarter;\n \n private ExtractorDataDuplicator> cmStarter;\n \n /**\n * Creates a new {@link PipelineAnalysis}.\n * \n * @param config The global configuration.\n */\n public PipelineAnalysis(@NonNull Configuration config) {\n super(config);\n }\n \n /**\n * The {@link PipelineAnalysis} that is the current main analysis in this execution. May be null if no\n * {@link PipelineAnalysis} is the main analysis component.\n *\n * @return The current {@link PipelineAnalysis} instance.\n */\n static PipelineAnalysis getInstance() {\n return instance;\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the variability model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the variability model.\n */\n protected @NonNull AnalysisComponent getVmComponent() {\n return vmStarter.createNewStartingComponent(config);\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the build model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the build model.\n */\n protected @NonNull AnalysisComponent getBmComponent() {\n return bmStarter.createNewStartingComponent(config);\n }\n \n /**\n * Returns the {@link AnalysisComponent} that provides the code model from the extractors.\n * \n * @return The {@link AnalysisComponent} that provides the code model.\n */\n protected @NonNull AnalysisComponent> getCmComponent() {\n return cmStarter.createNewStartingComponent(config);\n }\n \n /**\n * The collection that {@link AnalysisComponent}s should write their intermediate output to.\n * \n * @return The {@link ITableCollection} to write output to.\n */\n ITableCollection getResultCollection() {\n return resultCollection;\n }\n \n /**\n * Creates the result collection from the user settings.\n * \n * @return The result collection to store files in.\n * \n * @throws SetUpException If creating the result collection fails.\n */\n private ITableCollection createResultCollection() throws SetUpException {\n String outputSuffix = config.getValue(DefaultSettings.ANALYSIS_RESULT);\n File outputFile = new File(getOutputDir(), Timestamp.INSTANCE.getFilename(\n config.getValue(DefaultSettings.ANALYSIS_RESULT_NAME), outputSuffix));\n \n try {\n return TableCollectionWriterFactory.INSTANCE.createCollection(outputFile);\n } catch (IOException e) {\n throw new SetUpException(\"Can't create output for suffix \" + outputSuffix, e);\n }\n }\n \n /**\n * Creates the pipeline.\n * \n * @return The \"main\" (i.e. the last) component of the pipeline.\n * \n * @throws SetUpException If setting up the pipeline fails.\n */\n protected abstract @NonNull AnalysisComponent> createPipeline() throws SetUpException;\n\n @Override\n public void run() {\n Thread.currentThread().setName(\"AnalysisPipelineController\");\n try {\n vmStarter = new ExtractorDataDuplicator<>(vmProvider, false, \"VM\");\n bmStarter = new ExtractorDataDuplicator<>(bmProvider, false, \"BM\");\n cmStarter = new ExtractorDataDuplicator<>(cmProvider, true, \"CM\");\n \n try {\n resultCollection = createResultCollection();\n } catch (SetUpException e) {\n LOGGER.logException(\"Couldn't create output collection based on user configuration; \"\n + \"falling back to CSV\", e);\n \n resultCollection = new CsvFileCollection(new File(getOutputDir(), \n \"Analysis_\" + Timestamp.INSTANCE.getFileTimestamp()));\n }\n \n instance = this;\n \n AnalysisComponent> mainComponent = createPipeline();\n \n if (config.getValue(DefaultSettings.ANALYSIS_PIPELINE_START_EXTRACTORS)) {\n // start all extractors; this is needed here because the analysis components will most likely poll them\n // in order, which means that the extractors would not run in parallel\n vmStarter.start();\n bmStarter.start();\n cmStarter.start();\n }\n \n if (mainComponent instanceof JoinComponent) {\n joinSplitComponentFull((JoinComponent) mainComponent);\n \n } else {\n pollAndWriteOutput(mainComponent);\n }\n \n LOGGER.logDebug(\"Analysis components done\");\n \n try {\n LOGGER.logDebug(\"Closing result collection\");\n resultCollection.close();\n \n for (File file : resultCollection.getFiles()) {\n addOutputFile(file);\n }\n } catch (IOException e) {\n LOGGER.logException(\"Exception while closing output file\", e);\n }\n \n } catch (SetUpException e) {\n LOGGER.logException(\"Exception while setting up\", e);\n }\n }\n\n /**\n * Part of {@link #run()} to handle {@link JoinComponent}s. This method joins all components in parallel.\n * \n * @param mainComponent The analysis, which is joining results of multiple other components.\n */\n private void joinSplitComponentFull(@NonNull JoinComponent mainComponent) {\n List threads = new ArrayList<>(mainComponent.getInputs().length);\n \n for (AnalysisComponent> component : mainComponent.getInputs()) {\n Thread th = new Thread(() -> {\n pollAndWriteOutput(component);\n }, \"AnalysisPipelineControllerOutputThread\");\n threads.add(th);\n th.setDaemon(true);\n th.start();\n }\n \n for (Thread th : threads) {\n try {\n th.join();\n } catch (InterruptedException e) {\n }\n }\n }\n \n /**\n * Polls all output from the given component and writes it to the output file.\n * \n * @param component The component to read the output from.\n */\n private void pollAndWriteOutput(@NonNull AnalysisComponent> component) {\n LOGGER.logDebug2(\"Starting and polling output of analysis component (\", component.getClass().getSimpleName(),\n \")...\");\n \n try (ITableWriter writer = resultCollection.getWriter(component.getResultName())) {\n Object result;\n while ((result = component.getNextResult()) != null) {\n LOGGER.logDebug2(\"Got analysis result: \", result.toString());\n \n writer.writeObject(result);\n }\n } catch (IOException e) {\n LOGGER.logException(\"Exception while writing output file\", e);\n }\n }\n \n /**\n * A class for duplicating the extractor data. This way, multiple analysis components can have the same models\n * as their input data.\n * \n * @param The type of model to duplicate.\n */\n private static class ExtractorDataDuplicator implements Runnable {\n \n private @NonNull AbstractProvider provider;\n \n private boolean multiple;\n \n private @NonNull List<@NonNull StartingComponent> startingComponents;\n \n private boolean started;\n \n private @NonNull String type;\n \n /**\n * Creates a new ExtractorDataDuplicator.\n * \n * @param provider The provider to get the data from.\n * @param multiple Whether the provider should be polled multiple times or just once.\n * @param type The type of duplicator component (\"CM\", \"BM\" or \"VM\").\n */\n public ExtractorDataDuplicator(@NonNull AbstractProvider provider, boolean multiple, @NonNull String type) {\n this.provider = provider;\n this.multiple = multiple;\n this.type = type;\n startingComponents = new LinkedList<>();\n }\n \n /**\n * Creates a new starting component that will get its own copy of the data from us.\n * \n * @param config The configuration to create the component with.\n * \n * @return The starting component that can be used as input data for other analysis components.\n */\n public @NonNull StartingComponent createNewStartingComponent(@NonNull Configuration config) {\n \n StartingComponent component = new StartingComponent<>(config, this, type);\n startingComponents.add(component);\n return component;\n }\n \n /**\n * Adds the given data element to all starting components.\n * \n * @param data The data to add.\n */\n private void addToAllComponents(@NonNull T data) {\n for (StartingComponent component : startingComponents) {\n component.addResult(data);\n }\n }\n \n /**\n * Starts a new thread that copies the extractor data to all stating components created up until now.\n * This method ensures that this thread is only started once, no matter how often this method is called.\n */\n public void start() {\n synchronized (this) {\n if (!started) {\n new Thread(this, \"ExtractorDataDuplicator\").start();\n started = true;\n }\n }\n }\n \n @Override\n public void run() {\n if (multiple) {\n T data;\n while ((data = provider.getNextResult()) != null) {\n addToAllComponents(data);\n }\n \n ExtractorException exc;\n while ((exc = provider.getNextException()) != null) {\n LOGGER.logException(\"Got extractor exception\", exc);\n }\n } else {\n T data = provider.getResult();\n if (data != null) {\n addToAllComponents(data);\n }\n \n ExtractorException exc = provider.getException();\n if (exc != null) {\n LOGGER.logException(\"Got extractor exception\", exc);\n }\n }\n \n for (StartingComponent component : startingComponents) {\n synchronized (component) {\n component.done = true;\n component.notifyAll();\n }\n }\n }\n \n }\n \n /**\n * A starting component for the analysis pipeline. This is used to pass the extractor data to the analysis\n * components. This class does nothing; it is only used by {@link ExtractorDataDuplicator}.\n * \n * @param The type of result data that this produces.\n */\n private static class StartingComponent extends AnalysisComponent {\n\n private boolean done = false;\n \n private @NonNull ExtractorDataDuplicator duplicator;\n \n private @NonNull String name;\n \n /**\n * Creates a new starting component.\n * \n * @param config The global configuration.\n * @param duplicator The {@link ExtractorDataDuplicator} to start when this component is started\n * (start on demand).\n * @param type The type of starting component (\"CM\", \"BM\" or \"VM\").\n */\n public StartingComponent(@NonNull Configuration config, @NonNull ExtractorDataDuplicator duplicator,\n @NonNull String type) {\n super(config);\n this.duplicator = duplicator;\n this.name = type + \" StartingComponent\";\n }\n\n @Override\n protected void execute() {\n duplicator.start();\n \n // wait until the duplicator tells us that we are done\n synchronized (this) {\n while (!done) {\n try {\n wait();\n } catch (InterruptedException e) {\n }\n }\n }\n }\n\n @Override\n public String getResultName() {\n return name;\n }\n \n @Override\n boolean isInternalHelperComponent() {\n return true;\n }\n \n }\n\n}\n"},"message":{"kind":"string","value":"ExtractorDataDuplicator: Don't log every extractor exception to [error]"},"old_file":{"kind":"string","value":"src/net/ssehub/kernel_haven/analysis/PipelineAnalysis.java"},"subject":{"kind":"string","value":"ExtractorDataDuplicator: Don't log every extractor exception to [error]"}}},{"rowIdx":145819,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"9bb0fdd1787ad259533399509bd5c253df8bdf58"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"vatbub/fokLauncher,vatbub/fokLauncher"},"new_contents":{"kind":"string","value":"package view;\r\n\r\nimport java.awt.Desktop;\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.net.URI;\r\nimport java.net.URISyntaxException;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\nimport java.util.ResourceBundle;\r\nimport java.util.logging.Level;\r\nimport applist.App;\r\nimport applist.AppList;\r\nimport common.Common;\r\nimport common.AppConfig;\r\nimport common.HidableUpdateProgressDialog;\r\nimport common.Internet;\r\nimport common.Prefs;\r\nimport common.UpdateChecker;\r\nimport common.UpdateInfo;\r\nimport common.Version;\r\nimport common.VersionList;\r\nimport extended.CustomListCell;\r\nimport extended.GuiLanguage;\r\nimport extended.VersionMenuItem;\r\nimport javafx.application.Application;\r\nimport javafx.application.Platform;\r\nimport javafx.beans.binding.Bindings;\r\nimport javafx.beans.value.ChangeListener;\r\nimport javafx.beans.value.ObservableValue;\r\nimport javafx.collections.FXCollections;\r\nimport javafx.collections.ObservableList;\r\nimport javafx.collections.transformation.FilteredList;\r\nimport javafx.event.ActionEvent;\r\nimport javafx.fxml.FXML;\r\nimport javafx.fxml.FXMLLoader;\r\nimport javafx.scene.Parent;\r\nimport javafx.scene.Scene;\r\nimport javafx.scene.control.Alert;\r\nimport javafx.scene.control.Button;\r\nimport javafx.scene.control.CheckBox;\r\nimport javafx.scene.control.ComboBox;\r\nimport javafx.scene.control.ContextMenu;\r\nimport javafx.scene.control.Hyperlink;\r\nimport javafx.scene.control.Label;\r\nimport javafx.scene.control.ListView;\r\nimport javafx.scene.control.Menu;\r\nimport javafx.scene.control.MenuItem;\r\nimport javafx.scene.control.ProgressBar;\r\nimport javafx.scene.control.SelectionMode;\r\nimport javafx.scene.control.TextField;\r\nimport javafx.scene.image.Image;\r\nimport javafx.scene.input.ClipboardContent;\r\nimport javafx.scene.input.DragEvent;\r\nimport javafx.scene.input.Dragboard;\r\nimport javafx.scene.input.MouseEvent;\r\nimport javafx.scene.input.TransferMode;\r\nimport javafx.scene.layout.GridPane;\r\nimport javafx.stage.FileChooser;\r\nimport javafx.stage.Stage;\r\nimport logging.FOKLogger;\r\nimport view.motd.MOTD;\r\nimport view.motd.MOTDDialog;\r\nimport view.updateAvailableDialog.UpdateAvailableDialog;\r\n\r\nimport org.apache.commons.io.FilenameUtils;\r\nimport org.apache.commons.lang.exception.ExceptionUtils;\r\nimport org.jdom2.JDOMException;\r\n\r\nimport com.rometools.rome.io.FeedException;\r\n\r\npublic class MainWindow extends Application implements HidableUpdateProgressDialog {\r\n\r\n\tprivate static FOKLogger log;\r\n\tpublic static AppConfig appConfig;\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tcommon.Common.setAppName(\"foklauncher\");\r\n\t\tlog = new FOKLogger(MainWindow.class.getName());\r\n\t\tprefs = new Prefs(MainWindow.class.getName());\r\n\r\n\t\t// Complete the update\r\n\t\tUpdateChecker.completeUpdate(args);\r\n\r\n\t\tfor (String arg : args) {\r\n\t\t\tif (arg.toLowerCase().matches(\"mockappversion=.*\")) {\r\n\t\t\t\t// Set the mock version\r\n\t\t\t\tString version = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockAppVersion(version);\r\n\t\t\t} else if (arg.toLowerCase().matches(\"mockbuildnumber=.*\")) {\r\n\t\t\t\t// Set the mock build number\r\n\t\t\t\tString buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockBuildNumber(buildnumber);\r\n\t\t\t} else if (arg.toLowerCase().matches(\"mockpackaging=.*\")) {\r\n\t\t\t\t// Set the mock packaging\r\n\t\t\t\tString packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockPackaging(packaging);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlaunch(args);\r\n\t}\r\n\r\n\tprivate static ResourceBundle bundle;\r\n\tprivate static Prefs prefs;\r\n\tprivate static final String enableSnapshotsPrefKey = \"enableSnapshots\";\r\n\tprivate static final String showLauncherAgainPrefKey = \"showLauncherAgain\";\r\n\tprivate static final String guiLanguagePrefKey = \"guiLanguage\";\r\n\tprivate static AppList apps;\r\n\tprivate static Stage stage;\r\n\tprivate static Thread downloadAndLaunchThread = new Thread();\r\n\tprivate static boolean launchSpecificVersionMenuCanceled = false;\r\n\tprivate static Locale systemDefaultLocale;\r\n\r\n\tprivate Runnable getAppListRunnable = new Runnable() {\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\t\t\ttry {\r\n\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tappList.setPlaceholder(new Label(bundle.getString(\"WaitForAppList\")));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t});\r\n\r\n\t\t\t\tapps = App.getAppList();\r\n\r\n\t\t\t\tObservableList items = FXCollections.observableArrayList();\r\n\t\t\t\tFilteredList filteredData = new FilteredList<>(items, s -> true);\r\n\r\n\t\t\t\tfor (App app : apps) {\r\n\t\t\t\t\titems.add(app);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Add filter functionality\r\n\t\t\t\tsearchField.textProperty().addListener(obs -> {\r\n\t\t\t\t\tString filter = searchField.getText();\r\n\t\t\t\t\tif (filter == null || filter.length() == 0) {\r\n\t\t\t\t\t\tfilteredData.setPredicate(s -> true);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tfilteredData.setPredicate(s -> s.getName().toLowerCase().contains(filter.toLowerCase()));\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\t// Build the context menu\r\n\t\t\t\tappList.setCellFactory(lv -> {\r\n\r\n\t\t\t\t\tCustomListCell cell = new CustomListCell();\r\n\r\n\t\t\t\t\tContextMenu contextMenu = new ContextMenu();\r\n\r\n\t\t\t\t\tMenu launchSpecificVersionItem = new Menu();\r\n\t\t\t\t\tlaunchSpecificVersionItem.textProperty()\r\n\t\t\t\t\t\t\t.bind(Bindings.format(bundle.getString(\"launchSpecificVersion\"), cell.itemProperty()));\r\n\r\n\t\t\t\t\tMenuItem dummyVersion = new MenuItem();\r\n\t\t\t\t\tdummyVersion.setText(bundle.getString(\"waitForVersionList\"));\r\n\t\t\t\t\tlaunchSpecificVersionItem.getItems().add(dummyVersion);\r\n\t\t\t\t\tlaunchSpecificVersionItem.setOnHiding(event2 -> {\r\n\t\t\t\t\t\tlaunchSpecificVersionMenuCanceled = true;\r\n\t\t\t\t\t});\r\n\t\t\t\t\tlaunchSpecificVersionItem.setOnShown(event -> {\r\n\t\t\t\t\t\tlaunchSpecificVersionMenuCanceled = false;\r\n\t\t\t\t\t\tThread buildContextMenuThread = new Thread() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tlog.getLogger().info(\"Getting available online versions...\");\r\n\t\t\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\t\t\t// Get available versions\r\n\t\t\t\t\t\t\t\tVersionList verList = new VersionList();\r\n\t\t\t\t\t\t\t\tif (!workOfflineCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t// Online mode enabled\r\n\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\tverList = app.getAllOnlineVersions();\r\n\t\t\t\t\t\t\t\t\t\tif (enableSnapshotsCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t\t\tverList.add(app.getLatestOnlineSnapshotVersion());\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\t\t\t\t\t// Something happened, pretend\r\n\t\t\t\t\t\t\t\t\t\t// offline mode\r\n\t\t\t\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t// Offline mode enabled\r\n\t\t\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t// Sort the list\r\n\t\t\t\t\t\t\t\tCollections.sort(verList);\r\n\r\n\t\t\t\t\t\t\t\t// Clear previous list\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.getItems().clear();\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\tfor (Version ver : verList) {\r\n\t\t\t\t\t\t\t\t\tVersionMenuItem menuItem = new VersionMenuItem();\r\n\t\t\t\t\t\t\t\t\tmenuItem.setVersion(ver);\r\n\t\t\t\t\t\t\t\t\tmenuItem.setText(ver.toString(false));\r\n\t\t\t\t\t\t\t\t\tmenuItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\t\t\t\t\t// Launch the download\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread = new Thread() {\r\n\t\t\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// Attach the on app\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// exit handler if\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// required\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (launchLauncherAfterAppExitCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlatform.setImplicitExit(false);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.addEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlatform.setImplicitExit(true);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.removeEventHandlerWhenLaunchedAppExits(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshowLauncherAgain);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.downloadIfNecessaryAndLaunch(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance, menuItem.getVersion(),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tworkOfflineCheckbox.isSelected());\r\n\t\t\t\t\t\t\t\t\t\t\t\t} catch (IOException | JDOMException e) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"An error occurred: \\n\" + ExceptionUtils.getStackTrace(e));\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread.setName(\"downloadAndLaunchThread\");\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread.start();\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.getItems().add(menuItem);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tif (!launchSpecificVersionMenuCanceled) {\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.hide();\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.show();\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\tif (!cell.getItem().isSpecificVersionListLoaded()) {\r\n\t\t\t\t\t\t\tbuildContextMenuThread.setName(\"buildContextMenuThread\");\r\n\t\t\t\t\t\t\tbuildContextMenuThread.start();\r\n\t\t\t\t\t\t\tcell.getItem().setSpecificVersionListLoaded(true);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tMenu deleteItem = new Menu();\r\n\t\t\t\t\tdeleteItem.textProperty()\r\n\t\t\t\t\t\t\t.bind(Bindings.format(bundle.getString(\"deleteVersion\"), cell.itemProperty()));\r\n\t\t\t\t\tMenuItem dummyVersion2 = new MenuItem();\r\n\t\t\t\t\tdummyVersion2.setText(bundle.getString(\"waitForVersionList\"));\r\n\t\t\t\t\tdeleteItem.getItems().add(dummyVersion2);\r\n\r\n\t\t\t\t\tdeleteItem.setOnShown(event -> {\r\n\t\t\t\t\t\t// App app = apps.get(cell.getIndex());\r\n\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\tif (!app.isDeletableVersionListLoaded()) {\r\n\t\t\t\t\t\t\t// Get deletable versions\r\n\t\t\t\t\t\t\tapp.setDeletableVersionListLoaded(true);\r\n\t\t\t\t\t\t\tlog.getLogger().info(\"Getting deletable versions...\");\r\n\t\t\t\t\t\t\tdeleteItem.getItems().clear();\r\n\r\n\t\t\t\t\t\t\tVersionList verList = new VersionList();\r\n\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\tCollections.sort(verList);\r\n\r\n\t\t\t\t\t\t\tfor (Version ver : verList) {\r\n\t\t\t\t\t\t\t\tVersionMenuItem menuItem = new VersionMenuItem();\r\n\t\t\t\t\t\t\t\tmenuItem.setVersion(ver);\r\n\t\t\t\t\t\t\t\tmenuItem.setText(ver.toString(false));\r\n\t\t\t\t\t\t\t\tmenuItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\t\t\t\t// Delete the file\r\n\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.delete(menuItem.getVersion());\r\n\t\t\t\t\t\t\t\t\t} finally {\r\n\t\t\t\t\t\t\t\t\t\tupdateLaunchButton();\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t// Update the list the next time the\r\n\t\t\t\t\t\t\t\t\t// user opens it as it has changed\r\n\t\t\t\t\t\t\t\t\tapp.setDeletableVersionListLoaded(false);\r\n\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tdeleteItem.getItems().add(menuItem);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\tdeleteItem.hide();\r\n\t\t\t\t\t\t\t\t\tdeleteItem.show();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tMenuItem exportInfoItem = new MenuItem();\r\n\t\t\t\t\texportInfoItem.setText(bundle.getString(\"exportInfo\"));\r\n\t\t\t\t\texportInfoItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\tFileChooser fileChooser = new FileChooser();\r\n\t\t\t\t\t\tfileChooser.getExtensionFilters()\r\n\t\t\t\t\t\t\t\t.addAll(new FileChooser.ExtensionFilter(\"FOK-Launcher-File\", \"*.foklauncher\"));\r\n\t\t\t\t\t\tfileChooser.setTitle(\"Save Image\");\r\n\t\t\t\t\t\tFile file = fileChooser.showSaveDialog(stage);\r\n\t\t\t\t\t\tif (file != null) {\r\n\t\t\t\t\t\t\tlog.getLogger().info(\"Exporting info...\");\r\n\t\t\t\t\t\t\t// App app = apps.get(cell.getIndex());\r\n\t\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tlog.getLogger().info(\"Exporting app info of app \" + app.getName() + \" to file: \"\r\n\t\t\t\t\t\t\t\t\t\t+ file.getAbsolutePath());\r\n\t\t\t\t\t\t\t\tapp.exportInfo(file);\r\n\t\t\t\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcontextMenu.getItems().addAll(launchSpecificVersionItem, deleteItem, exportInfoItem);\r\n\r\n\t\t\t\t\tMenuItem removeImportedApp = new MenuItem();\r\n\t\t\t\t\tcontextMenu.setOnShowing(event5 -> {\r\n\t\t\t\t\t\tApp app = cell.getItem();\r\n\t\t\t\t\t\tif (app.isImported()) {\r\n\t\t\t\t\t\t\tremoveImportedApp.setText(\"Remove this app from this list\");\r\n\t\t\t\t\t\t\tremoveImportedApp.setOnAction(event3 -> {\r\n\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\tapp.removeFromImportedAppList();\r\n\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.loadAppList();\r\n\t\t\t\t\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString());\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\tcontextMenu.getItems().add(removeImportedApp);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcontextMenu.setOnHidden(event5 -> {\r\n\t\t\t\t\t\t// Remove the removeImportedApp-Item again if it exists\r\n\t\t\t\t\t\tif (contextMenu.getItems().contains(removeImportedApp)) {\r\n\t\t\t\t\t\t\tcontextMenu.getItems().remove(removeImportedApp);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {\r\n\t\t\t\t\t\tif (isNowEmpty) {\r\n\t\t\t\t\t\t\tcell.setContextMenu(null);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tcell.setContextMenu(contextMenu);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\treturn cell;\r\n\t\t\t\t});\r\n\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tappList.setItems(filteredData);\r\n\t\t\t\t\t\tappList.setPlaceholder(new Label(bundle.getString(\"emptyAppList\")));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t});\r\n\r\n\t\t\t} catch (JDOMException | IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\tcurrentMainWindowInstance\r\n\t\t\t\t\t\t.showErrorMessage(\"An error occurred: \\n\" + e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n\t * The thread that gets the app list\r\n\t */\r\n\tprivate Thread getAppListThread;\r\n\r\n\t/**\r\n\t * This reference always refers to the currently used instance of the\r\n\t * MainWidow. The purpose of this field that {@code this} can be accessed in\r\n\t * a convenient way in static methods.\r\n\t */\r\n\tprivate static MainWindow currentMainWindowInstance;\r\n\r\n\tprivate static App currentlySelectedApp = null;\r\n\r\n\t@FXML // ResourceBundle that was given to the FXMLLoader\r\n\tprivate ResourceBundle resources;\r\n\r\n\t@FXML // URL location of the FXML file that was given to the FXMLLoader\r\n\tprivate URL location;\r\n\r\n\t@FXML // fx:id=\"appList\"\r\n\tprivate ListView appList; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"searchField\"\r\n\tprivate TextField searchField; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"enableSnapshotsCheckbox\"\r\n\tprivate CheckBox enableSnapshotsCheckbox; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"launchButton\"\r\n\tprivate ProgressButton launchButton; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"launchLauncherAfterAppExitCheckbox\"\r\n\tprivate CheckBox launchLauncherAfterAppExitCheckbox; // Value injected by\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FXMLLoader\r\n\r\n\t@FXML // fx:id=\"languageSelector\"\r\n\tprivate ComboBox languageSelector; // Value injected by\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// FXMLLoader\r\n\r\n\t@FXML // fx:id=\"progressBar\"\r\n\tprivate ProgressBar progressBar; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"workOfflineCheckbox\"\r\n\tprivate CheckBox workOfflineCheckbox; // Value injected by FXMLLoader\r\n\r\n\t@FXML\r\n\t/**\r\n\t * fx:id=\"updateLink\"\r\n\t */\r\n\tprivate Hyperlink updateLink; // Value injected by FXMLLoader\r\n\r\n\t@FXML\r\n\t/**\r\n\t * fx:id=\"versionLabel\"\r\n\t */\r\n\tprivate Label versionLabel; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"settingsGridView\"\r\n\tprivate GridPane settingsGridView; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"appInfoButton\"\r\n\tprivate Button appInfoButton; // Value injected by FXMLLoader\r\n\r\n\t// Handler for ListView[fx:id=\"appList\"] onMouseClicked\r\n\t@FXML\r\n\tvoid appListOnMouseClicked(MouseEvent event) {\r\n\t\t// Currently not used\r\n\t}\r\n\r\n\t// Handler for AnchorPane[id=\"AnchorPane\"] onDragDetected\r\n\t@FXML\r\n\tvoid appListOnDragDetected(MouseEvent event) {\r\n\t\tif (currentlySelectedApp != null) {\r\n\t\t\tFile tempFile = new File(\r\n\t\t\t\t\tCommon.getAndCreateAppDataPath() + currentlySelectedApp.getMavenArtifactID() + \".foklauncher\");\r\n\t\t\ttry {\r\n\t\t\t\tcurrentlySelectedApp.exportInfo(tempFile);\r\n\t\t\t\tDragboard db = appList.startDragAndDrop(TransferMode.MOVE);\r\n\t\t\t\tClipboardContent content = new ClipboardContent();\r\n\t\t\t\tcontent.putFiles(Arrays.asList(tempFile));\r\n\t\t\t\tdb.setContent(content);\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Handler for ListView[fx:id=\"appList\"] onDragOver\r\n\t@FXML\r\n\tvoid mainFrameOnDragOver(DragEvent event) {\r\n\t\tDragboard db = event.getDragboard();\r\n\t\t// Only allow drag'n'drop for files and if no app list is currently\r\n\t\t// loading\r\n\t\tif (db.hasFiles() && !getAppListThread.isAlive()) {\r\n\t\t\t// Don't accept the drag if any file contained in the drag does not\r\n\t\t\t// have the *.foklauncher extension\r\n\t\t\tfor (File f : db.getFiles()) {\r\n\t\t\t\tif (!FilenameUtils.getExtension(f.getAbsolutePath()).equals(\"foklauncher\")) {\r\n\t\t\t\t\tevent.consume();\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tevent.acceptTransferModes(TransferMode.LINK);\r\n\t\t} else {\r\n\t\t\tevent.consume();\r\n\t\t}\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid mainFrameOnDragDropped(DragEvent event) {\r\n\t\tList files = event.getDragboard().getFiles();\r\n\r\n\t\tfor (File f : files) {\r\n\t\t\tlog.getLogger().info(\"Importing app from \" + f.getAbsolutePath() + \"...\");\r\n\t\t\ttry {\r\n\t\t\t\tApp.addImportedApp(f);\r\n\t\t\t\tcurrentMainWindowInstance.loadAppList();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString(), false);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static Runnable showLauncherAgain = new Runnable() {\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\r\n\t\t\t// reset the ui\r\n\t\t\ttry {\r\n\t\t\t\tcurrentMainWindowInstance.start(stage);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tlog.getLogger().log(Level.INFO,\r\n\t\t\t\t\t\t\"An error occurred while firing a handler for the LaunchedAppExited event, trying to run the handler using Platform.runLater...\",\r\n\t\t\t\t\t\te);\r\n\t\t\t}\r\n\t\t\tPlatform.setImplicitExit(true);\r\n\t\t}\r\n\t};\r\n\r\n\t@FXML\r\n\t/**\r\n\t * Handler for Hyperlink[fx:id=\"updateLink\"] onAction\r\n\t * \r\n\t * @param event\r\n\t * The event object that contains information about the event.\r\n\t */\r\n\tvoid updateLinkOnAction(ActionEvent event) {\r\n\t\t// Check for new version ignoring ignored updates\r\n\t\tThread updateThread = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tUpdateInfo update = UpdateChecker.isUpdateAvailableCompareAppVersion(AppConfig.getUpdateRepoBaseURL(),\r\n\t\t\t\t\t\tAppConfig.groupID, AppConfig.artifactID, AppConfig.getUpdateFileClassifier(),\r\n\t\t\t\t\t\tCommon.getPackaging());\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tnew UpdateAvailableDialog(update);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t};\r\n\t\tupdateThread.setName(\"manualUpdateThread\");\r\n\t\tupdateThread.start();\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid languageSelectorOnAction(ActionEvent event) {\r\n\t\tlog.getLogger().info(\"Switching gui language to: \"\r\n\t\t\t\t+ languageSelector.getItems().get(languageSelector.getSelectionModel().getSelectedIndex()));\r\n\t\tprefs.setPreference(guiLanguagePrefKey, languageSelector.getItems()\r\n\t\t\t\t.get(languageSelector.getSelectionModel().getSelectedIndex()).getLocale().getLanguage());\r\n\r\n\t\t// Restart gui\r\n\t\tboolean implicitExit = Platform.isImplicitExit();\r\n\t\tPlatform.setImplicitExit(false);\r\n\t\tstage.hide();\r\n\t\ttry {\r\n\t\t\tcurrentMainWindowInstance.start(stage);\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.INFO, \"An error occurred while setting a new gui language\", e);\r\n\t\t}\r\n\t\tPlatform.setImplicitExit(implicitExit);\r\n\t}\r\n\r\n\t// Handler for Button[fx:id=\"launchButton\"] onAction\r\n\t@FXML\r\n\tvoid launchButtonOnAction(ActionEvent event) {\r\n\t\tMainWindow gui = this;\r\n\r\n\t\tif (!downloadAndLaunchThread.isAlive()) {\r\n\t\t\t// Launch the download\r\n\t\t\tdownloadAndLaunchThread = new Thread() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\t// Attach the on app exit handler if required\r\n\t\t\t\t\t\tif (launchLauncherAfterAppExitCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\tPlatform.setImplicitExit(false);\r\n\t\t\t\t\t\t\tcurrentlySelectedApp.addEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tPlatform.setImplicitExit(true);\r\n\t\t\t\t\t\t\tcurrentlySelectedApp.removeEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tcurrentlySelectedApp.downloadIfNecessaryAndLaunch(enableSnapshotsCheckbox.isSelected(), gui,\r\n\t\t\t\t\t\t\t\tworkOfflineCheckbox.isSelected());\r\n\t\t\t\t\t} catch (IOException | JDOMException e) {\r\n\t\t\t\t\t\tgui.showErrorMessage(\"An error occurred: \\n\" + e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\tdownloadAndLaunchThread.setName(\"downloadAndLaunchThread\");\r\n\t\t\tdownloadAndLaunchThread.start();\r\n\t\t} else {\r\n\t\t\tcurrentlySelectedApp.cancelDownloadAndLaunch(gui);\r\n\t\t}\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"workOfflineCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid workOfflineCheckboxOnAction(ActionEvent event) {\r\n\t\tupdateLaunchButton();\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"launchLauncherAfterAppExitCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid launchLauncherAfterAppExitCheckboxOnAction(ActionEvent event) {\r\n\t\tprefs.setPreference(showLauncherAgainPrefKey,\r\n\t\t\t\tBoolean.toString(launchLauncherAfterAppExitCheckbox.isSelected()));\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid appInfoButtonOnAction(ActionEvent event) {\r\n\t\ttry {\r\n\t\t\tDesktop.getDesktop().browse(new URI(currentlySelectedApp.getAdditionalInfoURL().toString()));\r\n\t\t} catch (IOException | URISyntaxException e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void start(Stage primaryStage) throws Exception {\r\n\t\t// get the right resource bundle\r\n\t\tString guiLanguageCode = prefs.getPreference(guiLanguagePrefKey, \"\");\r\n\r\n\t\tif (guiLanguageCode.equals(\"\")) {\r\n\t\t\tif (systemDefaultLocale != null) {\r\n\t\t\t\tLocale.setDefault(systemDefaultLocale);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Get the specified bundle\r\n\t\t\tif (systemDefaultLocale == null) {\r\n\t\t\t\tsystemDefaultLocale = Locale.getDefault();\r\n\t\t\t}\r\n\t\t\tlog.getLogger().info(\"Setting language: \" + guiLanguageCode);\r\n\t\t\tLocale.setDefault(new Locale(guiLanguageCode));\r\n\t\t}\r\n\r\n\t\tbundle = ResourceBundle.getBundle(\"view.MainWindow\");\r\n\r\n\t\t// appConfig = new Config();\r\n\r\n\t\tstage = primaryStage;\r\n\t\ttry {\r\n\t\t\tThread updateThread = new Thread() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tUpdateInfo update = UpdateChecker.isUpdateAvailable(AppConfig.getUpdateRepoBaseURL(),\r\n\t\t\t\t\t\t\tAppConfig.groupID, AppConfig.artifactID, AppConfig.getUpdateFileClassifier(),\r\n\t\t\t\t\t\t\tCommon.getPackaging());\r\n\t\t\t\t\tif (update.showAlert) {\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tnew UpdateAvailableDialog(update);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tupdateThread.setName(\"updateThread\");\r\n\t\t\tupdateThread.start();\r\n\r\n\t\t\tParent root = FXMLLoader.load(getClass().getResource(\"MainWindow.fxml\"), bundle);\r\n\r\n\t\t\tScene scene = new Scene(root);\r\n\t\t\tscene.getStylesheets().add(getClass().getResource(\"MainWindow.css\").toExternalForm());\r\n\r\n\t\t\tprimaryStage.setTitle(bundle.getString(\"windowTitle\"));\r\n\r\n\t\t\tprimaryStage.setMinWidth(scene.getRoot().minWidth(0) + 70);\r\n\t\t\tprimaryStage.setMinHeight(scene.getRoot().minHeight(0) + 70);\r\n\r\n\t\t\tprimaryStage.setScene(scene);\r\n\r\n\t\t\t// Set Icon\r\n\t\t\tprimaryStage.getIcons().add(new Image(MainWindow.class.getResourceAsStream(\"icon.png\")));\r\n\r\n\t\t\tprimaryStage.show();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void stop() {\r\n\t\ttry {\r\n\t\t\tUpdateChecker.cancelUpdateCompletion();\r\n\t\t\tif (currentlySelectedApp != null) {\r\n\t\t\t\tcurrentlySelectedApp.cancelDownloadAndLaunch(this);\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE,\r\n\t\t\t\t\t\"An error occurred but is not relevant as we are currently in the shutdown process. Possible reasons for this exception are: You tried to modify a view but it is not shown any more on the screen; You tried to cancel the app download but no download was in progress.\",\r\n\t\t\t\t\te);\r\n\t\t}\r\n\t}\r\n\r\n\t@FXML // This method is called by the FXMLLoader when initialization is\r\n\t\t\t// complete\r\n\tvoid initialize() {\r\n\t\tassert launchButton != null : \"fx:id=\\\"launchButton\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert launchLauncherAfterAppExitCheckbox != null : \"fx:id=\\\"launchLauncherAfterAppExitCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert languageSelector != null : \"fx:id=\\\"languageSelector\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert versionLabel != null : \"fx:id=\\\"versionLabel\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert searchField != null : \"fx:id=\\\"searchField\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert appList != null : \"fx:id=\\\"appList\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert appInfoButton != null : \"fx:id=\\\"appInfoButton\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert progressBar != null : \"fx:id=\\\"progressBar\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert enableSnapshotsCheckbox != null : \"fx:id=\\\"enableSnapshotsCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert workOfflineCheckbox != null : \"fx:id=\\\"workOfflineCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert updateLink != null : \"fx:id=\\\"updateLink\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert settingsGridView != null : \"fx:id=\\\"settingsGridView\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\r\n\t\t// Initialize your logic here: all @FXML variables will have been\r\n\t\t// injected\r\n\r\n\t\t// Show messages of the day\r\n\t\tThread motdThread = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tMOTD motd;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tmotd = MOTD.getLatestMOTD(AppConfig.getMotdFeedUrl());\r\n\t\t\t\t\tif (!motd.isMarkedAsRead()) {\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tnew MOTDDialog(motd, motd.getEntry().getTitle());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (IllegalArgumentException | FeedException | IOException | ClassNotFoundException e) {\r\n\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\t\tmotdThread.setName(\"motdThread\");\r\n\t\tmotdThread.start();\r\n\r\n\t\tcurrentMainWindowInstance = this;\r\n\r\n\t\tenableSnapshotsCheckbox.setSelected(Boolean.parseBoolean(prefs.getPreference(enableSnapshotsPrefKey, \"false\")));\r\n\t\tlaunchLauncherAfterAppExitCheckbox\r\n\t\t\t\t.setSelected(Boolean.parseBoolean(prefs.getPreference(showLauncherAgainPrefKey, \"false\")));\r\n\r\n\t\ttry {\r\n\t\t\tversionLabel.setText(new Version(Common.getAppVersion(), Common.getBuildNumber()).toString(false));\r\n\t\t} catch (IllegalArgumentException e) {\r\n\t\t\tversionLabel.setText(Common.UNKNOWN_APP_VERSION);\r\n\t\t}\r\n\r\n\t\tprogressBar.setVisible(false);\r\n\r\n\t\t// Disable multiselect\r\n\t\tappList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);\r\n\r\n\t\tloadAvailableGuiLanguages();\r\n\r\n\t\t// Selection change listener\r\n\t\tappList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {\r\n\t\t\tpublic void changed(ObservableValue extends App> observable, App oldValue, App newValue) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tcurrentlySelectedApp = appList.getSelectionModel().getSelectedItem();\r\n\t\t\t\t} catch (ArrayIndexOutOfBoundsException e) {\r\n\t\t\t\t\tcurrentlySelectedApp = null;\r\n\t\t\t\t}\r\n\t\t\t\tupdateLaunchButton();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (!Internet.isConnected()) {\r\n\t\t\tworkOfflineCheckbox.setSelected(true);\r\n\t\t\tworkOfflineCheckbox.setDisable(true);\r\n\t\t}\r\n\r\n\t\tloadAppList();\r\n\t}\r\n\r\n\tprivate void loadAvailableGuiLanguages() {\r\n\t\tList supportedGuiLocales = Common.getLanguagesSupportedByResourceBundle(bundle);\r\n\t\tList convertedList = new ArrayList(supportedGuiLocales.size());\r\n\r\n\t\tfor (Locale lang : supportedGuiLocales) {\r\n\t\t\tconvertedList.add(new GuiLanguage(lang, bundle.getString(\"langaugeSelector.chooseAutomatically\")));\r\n\t\t}\r\n\t\tObservableList items = FXCollections.observableArrayList(convertedList);\r\n\t\tlanguageSelector.setItems(items);\r\n\r\n\t\tif (Locale.getDefault() != systemDefaultLocale) {\r\n\t\t\tGuiLanguage langToSelect = null;\r\n\r\n\t\t\tfor (GuiLanguage lang : convertedList) {\r\n\t\t\t\tif (Locale.getDefault().equals(lang.getLocale())) {\r\n\t\t\t\t\tlangToSelect = lang;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (langToSelect != null) {\r\n\t\t\t\tlanguageSelector.getSelectionModel().select(langToSelect);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Loads the app list using the {@link App#getAppList()}-method\r\n\t */\r\n\tprivate void loadAppList() {\r\n\t\tif (getAppListThread != null) {\r\n\t\t\t// If thread is not null and running, quit\r\n\t\t\tif (getAppListThread.isAlive()) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Thread is either null or not running anymore\r\n\t\tgetAppListThread = new Thread(getAppListRunnable);\r\n\t\tgetAppListThread.setName(\"getAppListThread\");\r\n\t\tgetAppListThread.start();\r\n\t}\r\n\r\n\tprivate void updateLaunchButton() {\r\n\t\tapps.reloadContextMenuEntriesOnShow();\r\n\r\n\t\tThread getAppStatus = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tApp checkedApp = currentlySelectedApp;\r\n\t\t\t\tboolean progressVisibleBefore = progressBar.isVisible();\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tlaunchButton.setDisable(true);\r\n\t\t\t\t\t\tlaunchButton.setDefaultButton(false);\r\n\t\t\t\t\t\tlaunchButton.setStyle(\"-fx-background-color: transparent;\");\r\n\t\t\t\t\t\tlaunchButton.setControlText(\"\");\r\n\t\t\t\t\t\tprogressBar.setPrefHeight(launchButton.getHeight());\r\n\t\t\t\t\t\tprogressBar.setVisible(true);\r\n\t\t\t\t\t\tprogressBar.setProgress(-1);\r\n\t\t\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.checkingVersionInfo\"));\r\n\t\t\t\t\t\tappInfoButton.setDisable(true);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\ttry {\r\n\t\t\t\t\tif (!workOfflineCheckbox.isSelected()) {\r\n\t\t\t\t\t\t// downloads are enabled\r\n\r\n\t\t\t\t\t\t// enable the additional info button if applicable\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tappInfoButton.setDisable(checkedApp.getAdditionalInfoURL() == null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tif (checkedApp.downloadRequired(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// download required\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.downloadAndLaunch\"));\r\n\t\t\t\t\t\t} else if (checkedApp.updateAvailable(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// Update available\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.updateAndLaunch\"));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Can launch immediately\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.launch\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t// downloads disabled\r\n\t\t\t\t\t\tif (checkedApp.downloadRequired(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// download required but disabled\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, true, bundle.getString(\"okButton.downloadAndLaunch\"));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Can launch immediately\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.launch\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (JDOMException | IOException e) {\r\n\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\r\n\t\t\t\t\t// Switch to offline mode\r\n\t\t\t\t\tworkOfflineCheckbox.setSelected(true);\r\n\t\t\t\t\tworkOfflineCheckbox.setDisable(true);\r\n\r\n\t\t\t\t\t// update launch button accordingly\r\n\t\t\t\t\tupdateLaunchButton();\r\n\r\n\t\t\t\t\t// Show error message\r\n\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(\r\n\t\t\t\t\t\t\tbundle.getString(\"updateLaunchButtonException\") + \"\\n\\n\" + ExceptionUtils.getStackTrace(e),\r\n\t\t\t\t\t\t\tfalse);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Do finishing touches to gui only if checkedApp still equals\r\n\t\t\t\t// currentlySelectedApp (make sure the user did not change the\r\n\t\t\t\t// selection in the meanwhile)\r\n\t\t\t\tif (checkedApp == currentlySelectedApp) {\r\n\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\tlaunchButton.setProgressText(\"\");\r\n\t\t\t\t\t\t\tprogressBar.setVisible(progressVisibleBefore);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t};\r\n\r\n\t\t// Only update the button caption if no download is running and an app\r\n\t\t// is selected\r\n\t\tif (!downloadAndLaunchThread.isAlive() && currentlySelectedApp != null) {\r\n\t\t\tgetAppStatus.setName(\"getAppStatus\");\r\n\t\t\tgetAppStatus.start();\r\n\t\t} else if (currentlySelectedApp == null) {\r\n\t\t\t// disable the button\r\n\t\t\tlaunchButton.setDisable(true);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void setLaunchButtonText(App checkedApp, boolean isDisabled, String text) {\r\n\t\t// Only update the button if the user did not change his selection\r\n\t\tif (checkedApp == currentlySelectedApp) {\r\n\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tlaunchButton.setDisable(isDisabled);\r\n\t\t\t\t\tlaunchButton.setDefaultButton(!isDisabled);\r\n\t\t\t\t\tlaunchButton.setStyle(\"\");\r\n\t\t\t\t\tlaunchButton.setControlText(text);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void hide() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tstage.hide();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"enableSnapshotsCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid enableSnapshotsCheckboxOnAction(ActionEvent event) {\r\n\t\tupdateLaunchButton();\r\n\t\tprefs.setPreference(enableSnapshotsPrefKey, Boolean.toString(enableSnapshotsCheckbox.isSelected()));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void preparePhaseStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tappList.setDisable(true);\r\n\t\t\t\tlaunchButton.setDisable(false);\r\n\t\t\t\tlaunchButton.setDefaultButton(false);\r\n\t\t\t\tprogressBar.setPrefHeight(launchButton.getHeight());\r\n\t\t\t\tlaunchButton.setStyle(\"-fx-background-color: transparent;\");\r\n\t\t\t\tlaunchButton.setControlText(bundle.getString(\"okButton.cancelLaunch\"));\r\n\t\t\t\tprogressBar.setVisible(true);\r\n\t\t\t\tprogressBar.setProgress(0 / 4.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.preparing\"));\r\n\r\n\t\t\t\tsettingsGridView.setDisable(true);\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void downloadStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(-1);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.downloading\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void installStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(1.0 / 2.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.installing\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void launchStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(2.0 / 2.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.launching\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\tpublic void showErrorMessage(String message) {\r\n\t\tshowErrorMessage(message, false);\r\n\t}\r\n\r\n\tpublic void showErrorMessage(String message, boolean closeWhenDialogIsClosed) {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tString finalMessage;\r\n\t\t\t\tif (closeWhenDialogIsClosed) {\r\n\t\t\t\t\tfinalMessage = message + \"\\n\\n\" + \"The app needs to close now.\";\r\n\t\t\t\t} else {\r\n\t\t\t\t\tfinalMessage = message;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tAlert alert = new Alert(Alert.AlertType.ERROR, finalMessage);\r\n\t\t\t\talert.show();\r\n\r\n\t\t\t\tThread t = new Thread() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\twhile (alert.isShowing()) {\r\n\t\t\t\t\t\t\t// wait for dialog to be closed\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (closeWhenDialogIsClosed) {\r\n\t\t\t\t\t\t\tSystem.err.println(\"Closing app after exception, good bye...\");\r\n\t\t\t\t\t\t\tPlatform.exit();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tt.setName(\"showErrorThread\");\r\n\t\t\t\tt.start();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void operationCanceled() {\r\n\t\tlog.getLogger().info(\"Operation cancelled.\");\r\n\t\tPlatform.setImplicitExit(true);\r\n\t\tappList.setDisable(false);\r\n\t\tprogressBar.setVisible(false);\r\n\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tlaunchButton.setProgressText(\"\");\r\n\t\t\t\tsettingsGridView.setDisable(false);\r\n\t\t\t\tupdateLaunchButton();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancelRequested() {\r\n\t\tif (progressBar != null) {\r\n\t\t\tprogressBar.setProgress(-1);\r\n\t\t\tlaunchButton.setProgressText(bundle.getString(\"cancelRequested\"));\r\n\t\t\tlaunchButton.setDisable(true);\r\n\t\t\tlog.getLogger().info(\"Requested to cancel the current operation, Cancel in progress...\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void downloadProgressChanged(double kilobytesDownloaded, double totalFileSizeInKB) {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(kilobytesDownloaded / totalFileSizeInKB);\r\n\r\n\t\t\t\tString downloadedString;\r\n\r\n\t\t\t\tif (kilobytesDownloaded < 1024) {\r\n\t\t\t\t\tdownloadedString = Double.toString(Math.round(kilobytesDownloaded * 100.0) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"kilobyte\");\r\n\t\t\t\t} else if ((kilobytesDownloaded / 1024) < 1024) {\r\n\t\t\t\t\tdownloadedString = Double.toString(Math.round((kilobytesDownloaded * 100.0) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"megabyte\");\r\n\t\t\t\t} else if (((kilobytesDownloaded / 1024) / 1024) < 1024) {\r\n\t\t\t\t\tdownloadedString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round(((kilobytesDownloaded * 100.0) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"gigabyte\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\tdownloadedString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round((((kilobytesDownloaded * 100.0) / 1024) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"terabyte\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tString totalString;\r\n\t\t\t\tif (totalFileSizeInKB < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round(totalFileSizeInKB * 100.0) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"kilobyte\");\r\n\t\t\t\t} else if ((totalFileSizeInKB / 1024) < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round((totalFileSizeInKB * 100.0) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"megabyte\");\r\n\t\t\t\t} else if (((totalFileSizeInKB / 1024) / 1024) < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round(((totalFileSizeInKB * 100.0) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"gigabyte\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttotalString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round((((totalFileSizeInKB * 100.0) / 1024) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"terabyte\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tlaunchButton.setProgressText(\r\n\t\t\t\t\t\tbundle.getString(\"progress.downloading\") + \"(\" + downloadedString + \"/\" + totalString + \")\");\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n}\r\n"},"new_file":{"kind":"string","value":"src/main/java/view/MainWindow.java"},"old_contents":{"kind":"string","value":"package view;\r\n\r\nimport java.awt.Desktop;\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.net.URI;\r\nimport java.net.URISyntaxException;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\nimport java.util.ResourceBundle;\r\nimport java.util.logging.Level;\r\nimport applist.App;\r\nimport applist.AppList;\r\nimport common.Common;\r\nimport common.AppConfig;\r\nimport common.HidableUpdateProgressDialog;\r\nimport common.Internet;\r\nimport common.Prefs;\r\nimport common.UpdateChecker;\r\nimport common.UpdateInfo;\r\nimport common.Version;\r\nimport common.VersionList;\r\nimport extended.CustomListCell;\r\nimport extended.GuiLanguage;\r\nimport extended.VersionMenuItem;\r\nimport javafx.application.Application;\r\nimport javafx.application.Platform;\r\nimport javafx.beans.binding.Bindings;\r\nimport javafx.beans.value.ChangeListener;\r\nimport javafx.beans.value.ObservableValue;\r\nimport javafx.collections.FXCollections;\r\nimport javafx.collections.ObservableList;\r\nimport javafx.collections.transformation.FilteredList;\r\nimport javafx.event.ActionEvent;\r\nimport javafx.fxml.FXML;\r\nimport javafx.fxml.FXMLLoader;\r\nimport javafx.scene.Parent;\r\nimport javafx.scene.Scene;\r\nimport javafx.scene.control.Alert;\r\nimport javafx.scene.control.Button;\r\nimport javafx.scene.control.CheckBox;\r\nimport javafx.scene.control.ComboBox;\r\nimport javafx.scene.control.ContextMenu;\r\nimport javafx.scene.control.Hyperlink;\r\nimport javafx.scene.control.Label;\r\nimport javafx.scene.control.ListView;\r\nimport javafx.scene.control.Menu;\r\nimport javafx.scene.control.MenuItem;\r\nimport javafx.scene.control.ProgressBar;\r\nimport javafx.scene.control.SelectionMode;\r\nimport javafx.scene.control.TextField;\r\nimport javafx.scene.image.Image;\r\nimport javafx.scene.input.ClipboardContent;\r\nimport javafx.scene.input.DragEvent;\r\nimport javafx.scene.input.Dragboard;\r\nimport javafx.scene.input.MouseEvent;\r\nimport javafx.scene.input.TransferMode;\r\nimport javafx.scene.layout.GridPane;\r\nimport javafx.stage.FileChooser;\r\nimport javafx.stage.Stage;\r\nimport logging.FOKLogger;\r\nimport view.motd.MOTD;\r\nimport view.motd.MOTDDialog;\r\nimport view.updateAvailableDialog.UpdateAvailableDialog;\r\n\r\nimport org.apache.commons.io.FilenameUtils;\r\nimport org.apache.commons.lang.exception.ExceptionUtils;\r\nimport org.jdom2.JDOMException;\r\n\r\nimport com.rometools.rome.io.FeedException;\r\n\r\npublic class MainWindow extends Application implements HidableUpdateProgressDialog {\r\n\r\n\tprivate static FOKLogger log;\r\n\tpublic static AppConfig appConfig;\r\n\r\n\tpublic static void main(String[] args) {\r\n\t\tcommon.Common.setAppName(\"foklauncher\");\r\n\t\tlog = new FOKLogger(MainWindow.class.getName());\r\n\t\tprefs = new Prefs(MainWindow.class.getName());\r\n\r\n\t\t// Complete the update\r\n\t\tUpdateChecker.completeUpdate(args);\r\n\r\n\t\tfor (String arg : args) {\r\n\t\t\tif (arg.toLowerCase().matches(\"mockappversion=.*\")) {\r\n\t\t\t\t// Set the mock version\r\n\t\t\t\tString version = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockAppVersion(version);\r\n\t\t\t} else if (arg.toLowerCase().matches(\"mockbuildnumber=.*\")) {\r\n\t\t\t\t// Set the mock build number\r\n\t\t\t\tString buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockBuildNumber(buildnumber);\r\n\t\t\t} else if (arg.toLowerCase().matches(\"mockpackaging=.*\")) {\r\n\t\t\t\t// Set the mock packaging\r\n\t\t\t\tString packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);\r\n\t\t\t\tCommon.setMockPackaging(packaging);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tlaunch(args);\r\n\t}\r\n\r\n\tprivate static ResourceBundle bundle;\r\n\tprivate static Prefs prefs;\r\n\tprivate static final String enableSnapshotsPrefKey = \"enableSnapshots\";\r\n\tprivate static final String showLauncherAgainPrefKey = \"showLauncherAgain\";\r\n\tprivate static final String guiLanguagePrefKey = \"guiLanguage\";\r\n\tprivate static AppList apps;\r\n\tprivate static Stage stage;\r\n\tprivate static Thread downloadAndLaunchThread = new Thread();\r\n\tprivate static boolean launchSpecificVersionMenuCanceled = false;\r\n\tprivate static Locale systemDefaultLocale;\r\n\r\n\tprivate Runnable getAppListRunnable = new Runnable() {\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\t\t\ttry {\r\n\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tappList.setPlaceholder(new Label(bundle.getString(\"WaitForAppList\")));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t});\r\n\r\n\t\t\t\tapps = App.getAppList();\r\n\r\n\t\t\t\tObservableList items = FXCollections.observableArrayList();\r\n\t\t\t\tFilteredList filteredData = new FilteredList<>(items, s -> true);\r\n\r\n\t\t\t\tfor (App app : apps) {\r\n\t\t\t\t\titems.add(app);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Add filter functionality\r\n\t\t\t\tsearchField.textProperty().addListener(obs -> {\r\n\t\t\t\t\tString filter = searchField.getText();\r\n\t\t\t\t\tif (filter == null || filter.length() == 0) {\r\n\t\t\t\t\t\tfilteredData.setPredicate(s -> true);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tfilteredData.setPredicate(s -> s.getName().toLowerCase().contains(filter.toLowerCase()));\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\t// Build the context menu\r\n\t\t\t\tappList.setCellFactory(lv -> {\r\n\r\n\t\t\t\t\tCustomListCell cell = new CustomListCell();\r\n\r\n\t\t\t\t\tContextMenu contextMenu = new ContextMenu();\r\n\r\n\t\t\t\t\tMenu launchSpecificVersionItem = new Menu();\r\n\t\t\t\t\tlaunchSpecificVersionItem.textProperty()\r\n\t\t\t\t\t\t\t.bind(Bindings.format(bundle.getString(\"launchSpecificVersion\"), cell.itemProperty()));\r\n\r\n\t\t\t\t\tMenuItem dummyVersion = new MenuItem();\r\n\t\t\t\t\tdummyVersion.setText(bundle.getString(\"waitForVersionList\"));\r\n\t\t\t\t\tlaunchSpecificVersionItem.getItems().add(dummyVersion);\r\n\t\t\t\t\tlaunchSpecificVersionItem.setOnHiding(event2 -> {\r\n\t\t\t\t\t\tlaunchSpecificVersionMenuCanceled = true;\r\n\t\t\t\t\t});\r\n\t\t\t\t\tlaunchSpecificVersionItem.setOnShown(event -> {\r\n\t\t\t\t\t\tlaunchSpecificVersionMenuCanceled = false;\r\n\t\t\t\t\t\tThread buildContextMenuThread = new Thread() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tlog.getLogger().info(\"Getting available online versions...\");\r\n\t\t\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\t\t\t// Get available versions\r\n\t\t\t\t\t\t\t\tVersionList verList = new VersionList();\r\n\t\t\t\t\t\t\t\tif (!workOfflineCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t// Online mode enabled\r\n\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\tverList = app.getAllOnlineVersions();\r\n\t\t\t\t\t\t\t\t\t\tif (enableSnapshotsCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t\t\tverList.add(app.getLatestOnlineSnapshotVersion());\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\t\t\t\t\t// Something happened, pretend\r\n\t\t\t\t\t\t\t\t\t\t// offline mode\r\n\t\t\t\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t// Offline mode enabled\r\n\t\t\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t// Sort the list\r\n\t\t\t\t\t\t\t\tCollections.sort(verList);\r\n\r\n\t\t\t\t\t\t\t\t// Clear previous list\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.getItems().clear();\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\t\tfor (Version ver : verList) {\r\n\t\t\t\t\t\t\t\t\tVersionMenuItem menuItem = new VersionMenuItem();\r\n\t\t\t\t\t\t\t\t\tmenuItem.setVersion(ver);\r\n\t\t\t\t\t\t\t\t\tmenuItem.setText(ver.toString(false));\r\n\t\t\t\t\t\t\t\t\tmenuItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\t\t\t\t\t// Launch the download\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread = new Thread() {\r\n\t\t\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// Attach the on app\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// exit handler if\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// required\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (launchLauncherAfterAppExitCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlatform.setImplicitExit(false);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.addEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tPlatform.setImplicitExit(true);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.removeEventHandlerWhenLaunchedAppExits(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshowLauncherAgain);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.downloadIfNecessaryAndLaunch(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance, menuItem.getVersion(),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tworkOfflineCheckbox.isSelected());\r\n\t\t\t\t\t\t\t\t\t\t\t\t} catch (IOException | JDOMException e) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(\"An error occurred: \\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ ExceptionUtils.getStackTrace(e));\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread.setName(\"downloadAndLaunchThread\");\r\n\t\t\t\t\t\t\t\t\t\tdownloadAndLaunchThread.start();\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.getItems().add(menuItem);\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tif (!launchSpecificVersionMenuCanceled) {\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.hide();\r\n\t\t\t\t\t\t\t\t\t\t\tlaunchSpecificVersionItem.show();\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\tif (!cell.getItem().isSpecificVersionListLoaded()) {\r\n\t\t\t\t\t\t\tbuildContextMenuThread.setName(\"buildContextMenuThread\");\r\n\t\t\t\t\t\t\tbuildContextMenuThread.start();\r\n\t\t\t\t\t\t\tcell.getItem().setSpecificVersionListLoaded(true);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tMenu deleteItem = new Menu();\r\n\t\t\t\t\tdeleteItem.textProperty()\r\n\t\t\t\t\t\t\t.bind(Bindings.format(bundle.getString(\"deleteVersion\"), cell.itemProperty()));\r\n\t\t\t\t\tMenuItem dummyVersion2 = new MenuItem();\r\n\t\t\t\t\tdummyVersion2.setText(bundle.getString(\"waitForVersionList\"));\r\n\t\t\t\t\tdeleteItem.getItems().add(dummyVersion2);\r\n\r\n\t\t\t\t\tdeleteItem.setOnShown(event -> {\r\n\t\t\t\t\t\t// App app = apps.get(cell.getIndex());\r\n\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\tif (!app.isDeletableVersionListLoaded()) {\r\n\t\t\t\t\t\t\t// Get deletable versions\r\n\t\t\t\t\t\t\tapp.setDeletableVersionListLoaded(true);\r\n\t\t\t\t\t\t\tlog.getLogger().info(\"Getting deletable versions...\");\r\n\t\t\t\t\t\t\tdeleteItem.getItems().clear();\r\n\r\n\t\t\t\t\t\t\tVersionList verList = new VersionList();\r\n\t\t\t\t\t\t\tverList = app.getCurrentlyInstalledVersions();\r\n\t\t\t\t\t\t\tCollections.sort(verList);\r\n\r\n\t\t\t\t\t\t\tfor (Version ver : verList) {\r\n\t\t\t\t\t\t\t\tVersionMenuItem menuItem = new VersionMenuItem();\r\n\t\t\t\t\t\t\t\tmenuItem.setVersion(ver);\r\n\t\t\t\t\t\t\t\tmenuItem.setText(ver.toString(false));\r\n\t\t\t\t\t\t\t\tmenuItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\t\t\t\t// Delete the file\r\n\t\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\t\tcurrentlySelectedApp.delete(menuItem.getVersion());\r\n\t\t\t\t\t\t\t\t\t} finally {\r\n\t\t\t\t\t\t\t\t\t\tupdateLaunchButton();\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t// Update the list the next time the\r\n\t\t\t\t\t\t\t\t\t// user opens it as it has changed\r\n\t\t\t\t\t\t\t\t\tapp.setDeletableVersionListLoaded(false);\r\n\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\t\tdeleteItem.getItems().add(menuItem);\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\t\tdeleteItem.hide();\r\n\t\t\t\t\t\t\t\t\tdeleteItem.show();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tMenuItem exportInfoItem = new MenuItem();\r\n\t\t\t\t\texportInfoItem.setText(bundle.getString(\"exportInfo\"));\r\n\t\t\t\t\texportInfoItem.setOnAction(event2 -> {\r\n\t\t\t\t\t\tFileChooser fileChooser = new FileChooser();\r\n\t\t\t\t\t\tfileChooser.getExtensionFilters()\r\n\t\t\t\t\t\t\t\t.addAll(new FileChooser.ExtensionFilter(\"FOK-Launcher-File\", \"*.foklauncher\"));\r\n\t\t\t\t\t\tfileChooser.setTitle(\"Save Image\");\r\n\t\t\t\t\t\tFile file = fileChooser.showSaveDialog(stage);\r\n\t\t\t\t\t\tif (file != null) {\r\n\t\t\t\t\t\t\tlog.getLogger().info(\"Exporting info...\");\r\n\t\t\t\t\t\t\t// App app = apps.get(cell.getIndex());\r\n\t\t\t\t\t\t\tApp app = cell.getItem();\r\n\r\n\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\tlog.getLogger().info(\"Exporting app info of app \" + app.getName() + \" to file: \"\r\n\t\t\t\t\t\t\t\t\t\t+ file.getAbsolutePath());\r\n\t\t\t\t\t\t\t\tapp.exportInfo(file);\r\n\t\t\t\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcontextMenu.getItems().addAll(launchSpecificVersionItem, deleteItem, exportInfoItem);\r\n\r\n\t\t\t\t\tMenuItem removeImportedApp = new MenuItem();\r\n\t\t\t\t\tcontextMenu.setOnShowing(event5 -> {\r\n\t\t\t\t\t\tApp app = cell.getItem();\r\n\t\t\t\t\t\tif (app.isImported()) {\r\n\t\t\t\t\t\t\tremoveImportedApp.setText(\"Remove this app from this list\");\r\n\t\t\t\t\t\t\tremoveImportedApp.setOnAction(event3 -> {\r\n\t\t\t\t\t\t\t\ttry {\r\n\t\t\t\t\t\t\t\t\tapp.removeFromImportedAppList();\r\n\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.loadAppList();\r\n\t\t\t\t\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString());\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\t\tcontextMenu.getItems().add(removeImportedApp);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcontextMenu.setOnHidden(event5 -> {\r\n\t\t\t\t\t\t// Remove the removeImportedApp-Item again if it exists\r\n\t\t\t\t\t\tif (contextMenu.getItems().contains(removeImportedApp)) {\r\n\t\t\t\t\t\t\tcontextMenu.getItems().remove(removeImportedApp);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tcell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {\r\n\t\t\t\t\t\tif (isNowEmpty) {\r\n\t\t\t\t\t\t\tcell.setContextMenu(null);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tcell.setContextMenu(contextMenu);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\treturn cell;\r\n\t\t\t\t});\r\n\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tappList.setItems(filteredData);\r\n\t\t\t\t\t\tappList.setPlaceholder(new Label(bundle.getString(\"emptyAppList\")));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t});\r\n\r\n\t\t\t} catch (JDOMException | IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\tcurrentMainWindowInstance\r\n\t\t\t\t\t\t.showErrorMessage(\"An error occurred: \\n\" + e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n\t * The thread that gets the app list\r\n\t */\r\n\tprivate Thread getAppListThread;\r\n\r\n\t/**\r\n\t * This reference always refers to the currently used instance of the\r\n\t * MainWidow. The purpose of this field that {@code this} can be accessed in\r\n\t * a convenient way in static methods.\r\n\t */\r\n\tprivate static MainWindow currentMainWindowInstance;\r\n\r\n\tprivate static App currentlySelectedApp = null;\r\n\r\n\t@FXML // ResourceBundle that was given to the FXMLLoader\r\n\tprivate ResourceBundle resources;\r\n\r\n\t@FXML // URL location of the FXML file that was given to the FXMLLoader\r\n\tprivate URL location;\r\n\r\n\t@FXML // fx:id=\"appList\"\r\n\tprivate ListView appList; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"searchField\"\r\n\tprivate TextField searchField; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"enableSnapshotsCheckbox\"\r\n\tprivate CheckBox enableSnapshotsCheckbox; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"launchButton\"\r\n\tprivate ProgressButton launchButton; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"launchLauncherAfterAppExitCheckbox\"\r\n\tprivate CheckBox launchLauncherAfterAppExitCheckbox; // Value injected by\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FXMLLoader\r\n\r\n\t@FXML // fx:id=\"languageSelector\"\r\n\tprivate ComboBox languageSelector; // Value injected by\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// FXMLLoader\r\n\r\n\t@FXML // fx:id=\"progressBar\"\r\n\tprivate ProgressBar progressBar; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"workOfflineCheckbox\"\r\n\tprivate CheckBox workOfflineCheckbox; // Value injected by FXMLLoader\r\n\r\n\t@FXML\r\n\t/**\r\n\t * fx:id=\"updateLink\"\r\n\t */\r\n\tprivate Hyperlink updateLink; // Value injected by FXMLLoader\r\n\r\n\t@FXML\r\n\t/**\r\n\t * fx:id=\"versionLabel\"\r\n\t */\r\n\tprivate Label versionLabel; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"settingsGridView\"\r\n\tprivate GridPane settingsGridView; // Value injected by FXMLLoader\r\n\r\n\t@FXML // fx:id=\"appInfoButton\"\r\n\tprivate Button appInfoButton; // Value injected by FXMLLoader\r\n\r\n\t// Handler for ListView[fx:id=\"appList\"] onMouseClicked\r\n\t@FXML\r\n\tvoid appListOnMouseClicked(MouseEvent event) {\r\n\t\t// Currently not used\r\n\t}\r\n\r\n\t// Handler for AnchorPane[id=\"AnchorPane\"] onDragDetected\r\n\t@FXML\r\n\tvoid appListOnDragDetected(MouseEvent event) {\r\n\t\tif (currentlySelectedApp != null) {\r\n\t\t\tFile tempFile = new File(\r\n\t\t\t\t\tCommon.getAndCreateAppDataPath() + currentlySelectedApp.getMavenArtifactID() + \".foklauncher\");\r\n\t\t\ttry {\r\n\t\t\t\tcurrentlySelectedApp.exportInfo(tempFile);\r\n\t\t\t\tDragboard db = appList.startDragAndDrop(TransferMode.MOVE);\r\n\t\t\t\tClipboardContent content = new ClipboardContent();\r\n\t\t\t\tcontent.putFiles(Arrays.asList(tempFile));\r\n\t\t\t\tdb.setContent(content);\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Handler for ListView[fx:id=\"appList\"] onDragOver\r\n\t@FXML\r\n\tvoid mainFrameOnDragOver(DragEvent event) {\r\n\t\tDragboard db = event.getDragboard();\r\n\t\t// Only allow drag'n'drop for files and if no app list is currently\r\n\t\t// loading\r\n\t\tif (db.hasFiles() && !getAppListThread.isAlive()) {\r\n\t\t\t// Don't accept the drag if any file contained in the drag does not\r\n\t\t\t// have the *.foklauncher extension\r\n\t\t\tfor (File f : db.getFiles()) {\r\n\t\t\t\tif (!FilenameUtils.getExtension(f.getAbsolutePath()).equals(\"foklauncher\")) {\r\n\t\t\t\t\tevent.consume();\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tevent.acceptTransferModes(TransferMode.LINK);\r\n\t\t} else {\r\n\t\t\tevent.consume();\r\n\t\t}\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid mainFrameOnDragDropped(DragEvent event) {\r\n\t\tList files = event.getDragboard().getFiles();\r\n\r\n\t\tfor (File f : files) {\r\n\t\t\tlog.getLogger().info(\"Importing app from \" + f.getAbsolutePath() + \"...\");\r\n\t\t\ttry {\r\n\t\t\t\tApp.addImportedApp(f);\r\n\t\t\t\tcurrentMainWindowInstance.loadAppList();\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\tcurrentMainWindowInstance.showErrorMessage(e.toString(), false);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static Runnable showLauncherAgain = new Runnable() {\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\r\n\t\t\t// reset the ui\r\n\t\t\ttry {\r\n\t\t\t\tcurrentMainWindowInstance.start(stage);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tlog.getLogger().log(Level.INFO,\r\n\t\t\t\t\t\t\"An error occurred while firing a handler for the LaunchedAppExited event, trying to run the handler using Platform.runLater...\",\r\n\t\t\t\t\t\te);\r\n\t\t\t}\r\n\t\t\tPlatform.setImplicitExit(true);\r\n\t\t}\r\n\t};\r\n\r\n\t@FXML\r\n\t/**\r\n\t * Handler for Hyperlink[fx:id=\"updateLink\"] onAction\r\n\t * \r\n\t * @param event\r\n\t * The event object that contains information about the event.\r\n\t */\r\n\tvoid updateLinkOnAction(ActionEvent event) {\r\n\t\t// Check for new version ignoring ignored updates\r\n\t\tThread updateThread = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tUpdateInfo update = UpdateChecker.isUpdateAvailableCompareAppVersion(AppConfig.getUpdateRepoBaseURL(),\r\n\t\t\t\t\t\tAppConfig.groupID, AppConfig.artifactID, AppConfig.getUpdateFileClassifier(),\r\n\t\t\t\t\t\tCommon.getPackaging());\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tnew UpdateAvailableDialog(update);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t};\r\n\t\tupdateThread.setName(\"manualUpdateThread\");\r\n\t\tupdateThread.start();\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid languageSelectorOnAction(ActionEvent event) {\r\n\t\tlog.getLogger().info(\"Switching gui language to: \"\r\n\t\t\t\t+ languageSelector.getItems().get(languageSelector.getSelectionModel().getSelectedIndex()));\r\n\t\tprefs.setPreference(guiLanguagePrefKey, languageSelector.getItems()\r\n\t\t\t\t.get(languageSelector.getSelectionModel().getSelectedIndex()).getLocale().getLanguage());\r\n\r\n\t\t// Restart gui\r\n\t\tboolean implicitExit = Platform.isImplicitExit();\r\n\t\tPlatform.setImplicitExit(false);\r\n\t\tstage.hide();\r\n\t\ttry {\r\n\t\t\tcurrentMainWindowInstance.start(stage);\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.INFO, \"An error occurred while setting a new gui language\", e);\r\n\t\t}\r\n\t\tPlatform.setImplicitExit(implicitExit);\r\n\t}\r\n\r\n\t// Handler for Button[fx:id=\"launchButton\"] onAction\r\n\t@FXML\r\n\tvoid launchButtonOnAction(ActionEvent event) {\r\n\t\tMainWindow gui = this;\r\n\r\n\t\tif (!downloadAndLaunchThread.isAlive()) {\r\n\t\t\t// Launch the download\r\n\t\t\tdownloadAndLaunchThread = new Thread() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\t// Attach the on app exit handler if required\r\n\t\t\t\t\t\tif (launchLauncherAfterAppExitCheckbox.isSelected()) {\r\n\t\t\t\t\t\t\tPlatform.setImplicitExit(false);\r\n\t\t\t\t\t\t\tcurrentlySelectedApp.addEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tPlatform.setImplicitExit(true);\r\n\t\t\t\t\t\t\tcurrentlySelectedApp.removeEventHandlerWhenLaunchedAppExits(showLauncherAgain);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tcurrentlySelectedApp.downloadIfNecessaryAndLaunch(enableSnapshotsCheckbox.isSelected(), gui,\r\n\t\t\t\t\t\t\t\tworkOfflineCheckbox.isSelected());\r\n\t\t\t\t\t} catch (IOException | JDOMException e) {\r\n\t\t\t\t\t\tgui.showErrorMessage(\"An error occurred: \\n\" + e.getClass().getName() + \"\\n\" + e.getMessage());\r\n\t\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\tdownloadAndLaunchThread.setName(\"downloadAndLaunchThread\");\r\n\t\t\tdownloadAndLaunchThread.start();\r\n\t\t} else {\r\n\t\t\tcurrentlySelectedApp.cancelDownloadAndLaunch(gui);\r\n\t\t}\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"workOfflineCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid workOfflineCheckboxOnAction(ActionEvent event) {\r\n\t\tupdateLaunchButton();\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"launchLauncherAfterAppExitCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid launchLauncherAfterAppExitCheckboxOnAction(ActionEvent event) {\r\n\t\tprefs.setPreference(showLauncherAgainPrefKey,\r\n\t\t\t\tBoolean.toString(launchLauncherAfterAppExitCheckbox.isSelected()));\r\n\t}\r\n\r\n\t@FXML\r\n\tvoid appInfoButtonOnAction(ActionEvent event) {\r\n\t\ttry {\r\n\t\t\tDesktop.getDesktop().browse(new URI(currentlySelectedApp.getAdditionalInfoURL().toString()));\r\n\t\t} catch (IOException | URISyntaxException e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void start(Stage primaryStage) throws Exception {\r\n\t\t// get the right resource bundle\r\n\t\tString guiLanguageCode = prefs.getPreference(guiLanguagePrefKey, \"\");\r\n\r\n\t\tif (guiLanguageCode.equals(\"\")) {\r\n\t\t\tif (systemDefaultLocale != null) {\r\n\t\t\t\tLocale.setDefault(systemDefaultLocale);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t// Get the specified bundle\r\n\t\t\tif (systemDefaultLocale == null) {\r\n\t\t\t\tsystemDefaultLocale = Locale.getDefault();\r\n\t\t\t}\r\n\t\t\tlog.getLogger().info(\"Setting language: \" + guiLanguageCode);\r\n\t\t\tLocale.setDefault(new Locale(guiLanguageCode));\r\n\t\t}\r\n\r\n\t\tbundle = ResourceBundle.getBundle(\"view.MainWindow\");\r\n\r\n\t\t// appConfig = new Config();\r\n\r\n\t\tstage = primaryStage;\r\n\t\ttry {\r\n\t\t\tThread updateThread = new Thread() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tUpdateInfo update = UpdateChecker.isUpdateAvailable(AppConfig.getUpdateRepoBaseURL(),\r\n\t\t\t\t\t\t\tAppConfig.groupID, AppConfig.artifactID, AppConfig.getUpdateFileClassifier(),\r\n\t\t\t\t\t\t\tCommon.getPackaging());\r\n\t\t\t\t\tif (update.showAlert) {\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tnew UpdateAvailableDialog(update);\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tupdateThread.setName(\"updateThread\");\r\n\t\t\tupdateThread.start();\r\n\r\n\t\t\tParent root = FXMLLoader.load(getClass().getResource(\"MainWindow.fxml\"), bundle);\r\n\r\n\t\t\tScene scene = new Scene(root);\r\n\t\t\tscene.getStylesheets().add(getClass().getResource(\"MainWindow.css\").toExternalForm());\r\n\r\n\t\t\tprimaryStage.setTitle(bundle.getString(\"windowTitle\"));\r\n\r\n\t\t\tprimaryStage.setMinWidth(scene.getRoot().minWidth(0) + 70);\r\n\t\t\tprimaryStage.setMinHeight(scene.getRoot().minHeight(0) + 70);\r\n\r\n\t\t\tprimaryStage.setScene(scene);\r\n\r\n\t\t\t// Set Icon\r\n\t\t\tprimaryStage.getIcons().add(new Image(MainWindow.class.getResourceAsStream(\"icon.png\")));\r\n\r\n\t\t\tprimaryStage.show();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void stop() {\r\n\t\ttry {\r\n\t\t\tUpdateChecker.cancelUpdateCompletion();\r\n\t\t\tif (currentlySelectedApp != null) {\r\n\t\t\t\tcurrentlySelectedApp.cancelDownloadAndLaunch(this);\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.getLogger().log(Level.SEVERE,\r\n\t\t\t\t\t\"An error occurred but is not relevant as we are currently in the shutdown process. Possible reasons for this exception are: You tried to modify a view but it is not shown any more on the screen; You tried to cancel the app download but no download was in progress.\",\r\n\t\t\t\t\te);\r\n\t\t}\r\n\t}\r\n\r\n\t@FXML // This method is called by the FXMLLoader when initialization is\r\n\t\t\t// complete\r\n\tvoid initialize() {\r\n\t\tassert launchButton != null : \"fx:id=\\\"launchButton\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert launchLauncherAfterAppExitCheckbox != null : \"fx:id=\\\"launchLauncherAfterAppExitCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert languageSelector != null : \"fx:id=\\\"languageSelector\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert versionLabel != null : \"fx:id=\\\"versionLabel\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert searchField != null : \"fx:id=\\\"searchField\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert appList != null : \"fx:id=\\\"appList\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert appInfoButton != null : \"fx:id=\\\"appInfoButton\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert progressBar != null : \"fx:id=\\\"progressBar\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert enableSnapshotsCheckbox != null : \"fx:id=\\\"enableSnapshotsCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert workOfflineCheckbox != null : \"fx:id=\\\"workOfflineCheckbox\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert updateLink != null : \"fx:id=\\\"updateLink\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\t\tassert settingsGridView != null : \"fx:id=\\\"settingsGridView\\\" was not injected: check your FXML file 'MainWindow.fxml'.\";\r\n\r\n\t\t// Initialize your logic here: all @FXML variables will have been\r\n\t\t// injected\r\n\r\n\t\t// Show messages of the day\r\n\t\tThread motdThread = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tMOTD motd;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tmotd = MOTD.getLatestMOTD(AppConfig.getMotdFeedUrl());\r\n\t\t\t\t\tif (!motd.isMarkedAsRead()) {\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tnew MOTDDialog(motd, motd.getEntry().getTitle());\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (IllegalArgumentException | FeedException | IOException | ClassNotFoundException e) {\r\n\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\t\tmotdThread.setName(\"motdThread\");\r\n\t\tmotdThread.start();\r\n\r\n\t\tcurrentMainWindowInstance = this;\r\n\r\n\t\tenableSnapshotsCheckbox.setSelected(Boolean.parseBoolean(prefs.getPreference(enableSnapshotsPrefKey, \"false\")));\r\n\t\tlaunchLauncherAfterAppExitCheckbox\r\n\t\t\t\t.setSelected(Boolean.parseBoolean(prefs.getPreference(showLauncherAgainPrefKey, \"false\")));\r\n\r\n\t\ttry {\r\n\t\t\tversionLabel.setText(new Version(Common.getAppVersion(), Common.getBuildNumber()).toString(false));\r\n\t\t} catch (IllegalArgumentException e) {\r\n\t\t\tversionLabel.setText(Common.UNKNOWN_APP_VERSION);\r\n\t\t}\r\n\r\n\t\tprogressBar.setVisible(false);\r\n\r\n\t\t// Disable multiselect\r\n\t\tappList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);\r\n\r\n\t\tloadAvailableGuiLanguages();\r\n\r\n\t\t// Selection change listener\r\n\t\tappList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {\r\n\t\t\tpublic void changed(ObservableValue extends App> observable, App oldValue, App newValue) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tcurrentlySelectedApp = appList.getSelectionModel().getSelectedItem();\r\n\t\t\t\t} catch (ArrayIndexOutOfBoundsException e) {\r\n\t\t\t\t\tcurrentlySelectedApp = null;\r\n\t\t\t\t}\r\n\t\t\t\tupdateLaunchButton();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tif (!Internet.isConnected()) {\r\n\t\t\tworkOfflineCheckbox.setSelected(true);\r\n\t\t\tworkOfflineCheckbox.setDisable(true);\r\n\t\t}\r\n\r\n\t\tloadAppList();\r\n\t}\r\n\r\n\tprivate void loadAvailableGuiLanguages() {\r\n\t\tList supportedGuiLocales = Common.getLanguagesSupportedByResourceBundle(bundle);\r\n\t\tList convertedList = new ArrayList(supportedGuiLocales.size());\r\n\r\n\t\tfor (Locale lang : supportedGuiLocales) {\r\n\t\t\tconvertedList.add(new GuiLanguage(lang, bundle.getString(\"langaugeSelector.chooseAutomatically\")));\r\n\t\t}\r\n\t\tObservableList items = FXCollections.observableArrayList(convertedList);\r\n\t\tlanguageSelector.setItems(items);\r\n\r\n\t\tif (Locale.getDefault() != systemDefaultLocale) {\r\n\t\t\tGuiLanguage langToSelect = null;\r\n\r\n\t\t\tfor (GuiLanguage lang : convertedList) {\r\n\t\t\t\tif (Locale.getDefault().equals(lang.getLocale())) {\r\n\t\t\t\t\tlangToSelect = lang;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (langToSelect != null) {\r\n\t\t\t\tlanguageSelector.getSelectionModel().select(langToSelect);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Loads the app list using the {@link App#getAppList()}-method\r\n\t */\r\n\tprivate void loadAppList() {\r\n\t\tif (getAppListThread != null) {\r\n\t\t\t// If thread is not null and running, quit\r\n\t\t\tif (getAppListThread.isAlive()) {\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Thread is either null or not running anymore\r\n\t\tgetAppListThread = new Thread(getAppListRunnable);\r\n\t\tgetAppListThread.setName(\"getAppListThread\");\r\n\t\tgetAppListThread.start();\r\n\t}\r\n\r\n\tprivate void updateLaunchButton() {\r\n\t\tapps.reloadContextMenuEntriesOnShow();\r\n\r\n\t\tThread getAppStatus = new Thread() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tApp checkedApp = currentlySelectedApp;\r\n\t\t\t\tboolean progressVisibleBefore = progressBar.isVisible();\r\n\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\tlaunchButton.setDisable(true);\r\n\t\t\t\t\t\tlaunchButton.setDefaultButton(false);\r\n\t\t\t\t\t\tlaunchButton.setStyle(\"-fx-background-color: transparent;\");\r\n\t\t\t\t\t\tlaunchButton.setControlText(\"\");\r\n\t\t\t\t\t\tprogressBar.setPrefHeight(launchButton.getHeight());\r\n\t\t\t\t\t\tprogressBar.setVisible(true);\r\n\t\t\t\t\t\tprogressBar.setProgress(-1);\r\n\t\t\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.checkingVersionInfo\"));\r\n\t\t\t\t\t\tappInfoButton.setDisable(true);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\ttry {\r\n\t\t\t\t\tif (!workOfflineCheckbox.isSelected()) {\r\n\t\t\t\t\t\t// downloads are enabled\r\n\r\n\t\t\t\t\t\t// enable the additional info button if applicable\r\n\t\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\t\tappInfoButton.setDisable(checkedApp.getAdditionalInfoURL() == null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tif (checkedApp.downloadRequired(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// download required\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.downloadAndLaunch\"));\r\n\t\t\t\t\t\t} else if (checkedApp.updateAvailable(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// Update available\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.updateAndLaunch\"));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Can launch immediately\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.launch\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t// downloads disabled\r\n\t\t\t\t\t\tif (checkedApp.downloadRequired(enableSnapshotsCheckbox.isSelected())) {\r\n\t\t\t\t\t\t\t// download required but disabled\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, true, bundle.getString(\"okButton.downloadAndLaunch\"));\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t// Can launch immediately\r\n\t\t\t\t\t\t\tsetLaunchButtonText(checkedApp, false, bundle.getString(\"okButton.launch\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (JDOMException | IOException e) {\r\n\t\t\t\t\tlog.getLogger().log(Level.SEVERE, \"An error occurred\", e);\r\n\r\n// Switch to offline mode\r\n\t\t\t\t\tworkOfflineCheckbox.setSelected(true);\r\n\t\t\t\t\tworkOfflineCheckbox.setDisable(true);\r\n\t\t\t\t\t\r\n\t\t\t\t\t// update launch button accordingly\r\n\t\t\t\t\tupdateLaunchButton();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Show error message\r\n\t\t\t\t\tcurrentMainWindowInstance.showErrorMessage(bundle.getString(\"updateLaunchButtonException\") + \"\\n\\n\"\r\n\t\t\t\t\t\t\t+ ExceptionUtils.getStackTrace(e), false);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Do finishing touches to gui only if checkedApp still equals\r\n\t\t\t\t// currentlySelectedApp (make sure the user did not change the\r\n\t\t\t\t// selection in the meanwhile)\r\n\t\t\t\tif (checkedApp == currentlySelectedApp) {\r\n\t\t\t\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t\t\t\t@Override\r\n\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\tlaunchButton.setProgressText(\"\");\r\n\t\t\t\t\t\t\tprogressBar.setVisible(progressVisibleBefore);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t};\r\n\r\n\t\t// Only update the button caption if no download is running and an app\r\n\t\t// is selected\r\n\t\tif (!downloadAndLaunchThread.isAlive() && currentlySelectedApp != null) {\r\n\t\t\tgetAppStatus.setName(\"getAppStatus\");\r\n\t\t\tgetAppStatus.start();\r\n\t\t} else if (currentlySelectedApp == null) {\r\n\t\t\t// disable the button\r\n\t\t\tlaunchButton.setDisable(true);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void setLaunchButtonText(App checkedApp, boolean isDisabled, String text) {\r\n\t\t// Only update the button if the user did not change his selection\r\n\t\tif (checkedApp == currentlySelectedApp) {\r\n\t\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tlaunchButton.setDisable(isDisabled);\r\n\t\t\t\t\tlaunchButton.setDefaultButton(!isDisabled);\r\n\t\t\t\t\tlaunchButton.setStyle(\"\");\r\n\t\t\t\t\tlaunchButton.setControlText(text);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void hide() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tstage.hide();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t// Handler for CheckBox[fx:id=\"enableSnapshotsCheckbox\"] onAction\r\n\t@FXML\r\n\tvoid enableSnapshotsCheckboxOnAction(ActionEvent event) {\r\n\t\tupdateLaunchButton();\r\n\t\tprefs.setPreference(enableSnapshotsPrefKey, Boolean.toString(enableSnapshotsCheckbox.isSelected()));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void preparePhaseStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tappList.setDisable(true);\r\n\t\t\t\tlaunchButton.setDisable(false);\r\n\t\t\t\tlaunchButton.setDefaultButton(false);\r\n\t\t\t\tprogressBar.setPrefHeight(launchButton.getHeight());\r\n\t\t\t\tlaunchButton.setStyle(\"-fx-background-color: transparent;\");\r\n\t\t\t\tlaunchButton.setControlText(bundle.getString(\"okButton.cancelLaunch\"));\r\n\t\t\t\tprogressBar.setVisible(true);\r\n\t\t\t\tprogressBar.setProgress(0 / 4.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.preparing\"));\r\n\r\n\t\t\t\tsettingsGridView.setDisable(true);\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void downloadStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(-1);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.downloading\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void installStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(1.0 / 2.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.installing\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void launchStarted() {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(2.0 / 2.0);\r\n\t\t\t\tlaunchButton.setProgressText(bundle.getString(\"progress.launching\"));\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n\tpublic void showErrorMessage(String message) {\r\n\t\tshowErrorMessage(message, false);\r\n\t}\r\n\r\n\tpublic void showErrorMessage(String message, boolean closeWhenDialogIsClosed) {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tAlert alert = new Alert(Alert.AlertType.ERROR, message + \"\\n\\n\" + \"The app needs to close now.\");\r\n\t\t\t\talert.show();\r\n\r\n\t\t\t\tThread t = new Thread() {\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\twhile (alert.isShowing()) {\r\n\t\t\t\t\t\t\t// wait for dialog to be closed\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tSystem.err.println(\"Closing app after exception, good bye...\");\r\n\t\t\t\t\t\tPlatform.exit();\r\n\t\t\t\t\t}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tt.setName(\"showErrorThread\");\r\n\t\t\t\tt.start();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void operationCanceled() {\r\n\t\tlog.getLogger().info(\"Operation cancelled.\");\r\n\t\tPlatform.setImplicitExit(true);\r\n\t\tappList.setDisable(false);\r\n\t\tprogressBar.setVisible(false);\r\n\t\tPlatform.runLater(new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tlaunchButton.setProgressText(\"\");\r\n\t\t\t\tsettingsGridView.setDisable(false);\r\n\t\t\t\tupdateLaunchButton();\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void cancelRequested() {\r\n\t\tif (progressBar != null) {\r\n\t\t\tprogressBar.setProgress(-1);\r\n\t\t\tlaunchButton.setProgressText(bundle.getString(\"cancelRequested\"));\r\n\t\t\tlaunchButton.setDisable(true);\r\n\t\t\tlog.getLogger().info(\"Requested to cancel the current operation, Cancel in progress...\");\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void downloadProgressChanged(double kilobytesDownloaded, double totalFileSizeInKB) {\r\n\t\tPlatform.runLater(new Runnable() {\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tprogressBar.setProgress(kilobytesDownloaded / totalFileSizeInKB);\r\n\r\n\t\t\t\tString downloadedString;\r\n\r\n\t\t\t\tif (kilobytesDownloaded < 1024) {\r\n\t\t\t\t\tdownloadedString = Double.toString(Math.round(kilobytesDownloaded * 100.0) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"kilobyte\");\r\n\t\t\t\t} else if ((kilobytesDownloaded / 1024) < 1024) {\r\n\t\t\t\t\tdownloadedString = Double.toString(Math.round((kilobytesDownloaded * 100.0) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"megabyte\");\r\n\t\t\t\t} else if (((kilobytesDownloaded / 1024) / 1024) < 1024) {\r\n\t\t\t\t\tdownloadedString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round(((kilobytesDownloaded * 100.0) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"gigabyte\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\tdownloadedString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round((((kilobytesDownloaded * 100.0) / 1024) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"terabyte\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tString totalString;\r\n\t\t\t\tif (totalFileSizeInKB < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round(totalFileSizeInKB * 100.0) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"kilobyte\");\r\n\t\t\t\t} else if ((totalFileSizeInKB / 1024) < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round((totalFileSizeInKB * 100.0) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"megabyte\");\r\n\t\t\t\t} else if (((totalFileSizeInKB / 1024) / 1024) < 1024) {\r\n\t\t\t\t\ttotalString = Double.toString(Math.round(((totalFileSizeInKB * 100.0) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"gigabyte\");\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttotalString = Double\r\n\t\t\t\t\t\t\t.toString(Math.round((((totalFileSizeInKB * 100.0) / 1024) / 1024) / 1024) / 100.0) + \" \"\r\n\t\t\t\t\t\t\t+ bundle.getString(\"terabyte\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tlaunchButton.setProgressText(\r\n\t\t\t\t\t\tbundle.getString(\"progress.downloading\") + \"(\" + downloadedString + \"/\" + totalString + \")\");\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t}\r\n\r\n}\r\n"},"message":{"kind":"string","value":"Fixed #23"},"old_file":{"kind":"string","value":"src/main/java/view/MainWindow.java"},"subject":{"kind":"string","value":"Fixed #23"}}},{"rowIdx":145820,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"1932e369273fc613171a5330155049250622aec0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"jitsi/libjitsi,jitsi/libjitsi,jitsi/libjitsi,jitsi/libjitsi"},"new_contents":{"kind":"string","value":"/*\n * Copyright @ 2015 Atlassian Pty Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jitsi.util;\n\nimport java.lang.reflect.*;\nimport java.util.*;\n\n/**\n *\n * @author Lyubomir Marinov\n */\npublic final class ArrayUtils\n{\n /**\n * Adds a specific element to a specific array with a specific component\n * type if the array does not contain the element yet.\n * \n * @param array the array to add element to\n * @param componentType the component type of array\n * @param element the element to add to array\n * @return an array with the specified componentType and\n * containing element. If array contained element\n * already, returns array.\n */\n @SuppressWarnings(\"unchecked\")\n public static T[] add(T[] array, Class componentType, T element)\n {\n if (element == null)\n throw new NullPointerException(\"element\");\n\n if (array == null)\n {\n array = (T[]) Array.newInstance(componentType, 1);\n }\n else\n {\n for (T a : array)\n {\n if (element.equals(a))\n return array;\n }\n\n T[] newArray\n = (T[]) Array.newInstance(componentType, array.length + 1);\n\n System.arraycopy(array, 0, newArray, 0, array.length);\n array = newArray;\n }\n array[array.length - 1] = element;\n return array;\n }\n\n /** Prevents the initialization of new {@code ArrayUtils} instances. */\n private ArrayUtils()\n {\n }\n\n /**\n * Concatenates two arrays.\n *\n * @param first\n * @param second\n * @param \n * @return\n */\n public static T[] concat(T[] first, T[] second)\n {\n if (first == null || first.length == 0)\n {\n return second;\n }\n else if (second == null || second.length == 0)\n {\n return first;\n }\n else\n {\n T[] result = Arrays.copyOf(first, first.length + second.length);\n System.arraycopy(second, 0, result, first.length, second.length);\n return result;\n }\n }\n}\n"},"new_file":{"kind":"string","value":"src/org/jitsi/util/ArrayUtils.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright @ 2015 Atlassian Pty Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jitsi.util;\n\nimport java.lang.reflect.*;\n\n/**\n *\n * @author Lyubomir Marinov\n */\npublic final class ArrayUtils\n{\n /**\n * Adds a specific element to a specific array with a specific component\n * type if the array does not contain the element yet.\n * \n * @param array the array to add element to\n * @param componentType the component type of array\n * @param element the element to add to array\n * @return an array with the specified componentType and\n * containing element. If array contained element\n * already, returns array.\n */\n @SuppressWarnings(\"unchecked\")\n public static T[] add(T[] array, Class componentType, T element)\n {\n if (element == null)\n throw new NullPointerException(\"element\");\n\n if (array == null)\n {\n array = (T[]) Array.newInstance(componentType, 1);\n }\n else\n {\n for (T a : array)\n {\n if (element.equals(a))\n return array;\n }\n\n T[] newArray\n = (T[]) Array.newInstance(componentType, array.length + 1);\n\n System.arraycopy(array, 0, newArray, 0, array.length);\n array = newArray;\n }\n array[array.length - 1] = element;\n return array;\n }\n\n /** Prevents the initialization of new {@code ArrayUtils} instances. */\n private ArrayUtils()\n {\n }\n}\n"},"message":{"kind":"string","value":"feat: Adds a method for array concatenation.\n"},"old_file":{"kind":"string","value":"src/org/jitsi/util/ArrayUtils.java"},"subject":{"kind":"string","value":"feat: Adds a method for array concatenation."}}},{"rowIdx":145821,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"031c1a413bb21bbf93c0b8499b46f37de02c9f1c"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android"},"new_contents":{"kind":"string","value":"package org.commcare.android.adapters;\n\nimport android.content.Context;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\n\nimport org.commcare.android.view.SquareButtonWithNotification;\nimport org.commcare.dalvik.R;\n\nimport java.util.HashMap;\nimport java.util.LinkedList;\n\n/**\n * Sets up home screen buttons and gives accessors for setting their visibility and listeners\n * Created by dancluna on 3/19/15.\n */\npublic class HomeScreenAdapter extends BaseAdapter {\n public static final String TAG = \"HomeScrnAdpt\";\n\n //region Buttons\n\n static final int[] buttonsResources = new int[]{\n R.layout.home_start_button,\n R.layout.home_savedforms_button,\n R.layout.home_incompleteforms_button,\n R.layout.home_sync_button,\n R.layout.home_disconnect_button,\n };\n\n static final HashMap buttonsIDsToResources = new HashMap() {{\n put(R.id.home_start_sqbn,R.layout.home_start_button);\n put(R.id.home_savedforms_sqbn,R.layout.home_savedforms_button);\n put(R.id.home_sync_sqbn,R.layout.home_sync_button);\n put(R.id.home_disconnect_sqbn,R.layout.home_disconnect_button);\n put(R.id.home_incompleteforms_sqbn,R.layout.home_incompleteforms_button);\n }};\n\n //endregion\n\n //region Private variables\n\n final View.OnClickListener[] buttonListeners = new View.OnClickListener[buttonsResources.length];\n\n final SquareButtonWithNotification[] buttons = new SquareButtonWithNotification[buttonsResources.length];\n\n private Context context;\n\n private boolean[] hiddenButtons = new boolean[buttonsResources.length];\n private boolean isInitialized = false;\n\n private LinkedList visibleButtons;\n\n //endregion\n\n //region Constructors\n\n public HomeScreenAdapter(Context c) {\n this.context = c;\n visibleButtons = new LinkedList();\n for (int i = 0; i < buttons.length; i++) {\n if (buttons[i] != null) {\n continue;\n }\n SquareButtonWithNotification button = (SquareButtonWithNotification)LayoutInflater.from(context)\n .inflate(buttonsResources[i], null, false);\n buttons[i] = button;\n Log.i(TAG, \"Added button \" + button + \"to position \" + i);\n\n View.OnClickListener listener = buttonListeners[i];\n // creating now, but set a clickListener before, so we'll add it to this button...\n if (listener != null) {\n button.setOnClickListener(listener);\n Log.i(TAG, \"Added onClickListener \" + listener + \" to button in position \" + i);\n }\n if (!hiddenButtons[i]) {\n visibleButtons.add(button);\n }\n }\n isInitialized = true;\n }\n\n //endregion\n\n //region Public API\n\n /**\n * Sets the onClickListener for the given button\n * @param resourceCode Android resource code (R.id.$button or R.layout.$button)\n * @param lookupID If set, will search for the button with the given R.id\n * @param listener OnClickListener for the button\n */\n public void setOnClickListenerForButton(int resourceCode, boolean lookupID, View.OnClickListener listener){\n int buttonIndex = getButtonIndex(resourceCode, lookupID);\n buttonListeners[buttonIndex] = listener;\n SquareButtonWithNotification button = (SquareButtonWithNotification) getItem(buttonIndex);\n if(button != null){\n button.setOnClickListener(listener);\n }\n }\n\n public SquareButtonWithNotification getButton(int resourceCode, boolean lookupID){\n return buttons[getButtonIndex(resourceCode, lookupID)];\n }\n\n public void setNotificationTextForButton(int resourceCode, boolean lookupID, String notificationText) {\n SquareButtonWithNotification button = getButton(resourceCode, lookupID);\n if (button != null) {\n button.setNotificationText(notificationText);\n notifyDataSetChanged();\n }\n }\n\n @Override\n public int getCount() {\n return visibleButtons.size();\n }\n\n @Override\n public Object getItem(int position) {\n return buttons[position];\n }\n\n @Override\n public long getItemId(int position) {\n return buttonsResources[position];\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (position < 0 || position >= getCount()) {\n return null;\n }\n if(convertView != null) {\n return convertView;\n } else {\n SquareButtonWithNotification btn = visibleButtons.get(position);\n\n if(btn == null) {\n Log.i(TAG,\"Unexpected null button\");\n }\n\n return btn;\n }\n }\n\n /**\n * Sets visibility for the button with the given resource code\n * @param resourceCode Android resource code (R.id.$button or R.layout.$button)\n * @param lookupID If set, will search for the button with the given R.id\n * @param isButtonHidden Button visibility state (true for hidden, false for visible)\n */\n public void setButtonVisibility(int resourceCode, boolean lookupID, boolean isButtonHidden){\n int index = getButtonIndex(resourceCode, lookupID);\n boolean toggled = isButtonHidden ^ hiddenButtons[index]; // checking if the button visibility was changed in this call\n hiddenButtons[index] = isButtonHidden;\n if (!toggled) {\n return;\n } // if the visibility was not changed, we don't need to do anything\n if (isButtonHidden) { // if the visibility was changed, we add/remove the button from the visible buttons' list\n visibleButtons.remove(buttons[index]);\n } else {\n visibleButtons.add(index, buttons[index]);\n }\n }\n\n //endregion\n\n //region Private methods\n\n\n\n /**\n * Returns the index of the button with the given resource code. If lookupID is set, will search for the button with the given R.id; if not, will search for the button with the given R.layout code.\n * @param resourceCode\n * @param lookupID\n * @return\n * @throws java.lang.IllegalArgumentException If the given resourceCode is not found\n */\n private int getButtonIndex(int resourceCode, boolean lookupID){\n int code = resourceCode;\n // if lookupID is set, we are mapping from an int in R.id to one in R.layout\n if(lookupID){\n Integer layoutCode = buttonsIDsToResources.get(resourceCode);\n if(layoutCode == null) throw new IllegalArgumentException(\"ID code not found: \" + resourceCode);\n code = layoutCode;\n }\n Integer buttonIndex = null;\n for (int i = 0; i < buttonsResources.length; i++) {\n if(code == buttonsResources[i]){\n buttonIndex = i;\n break;\n }\n }\n if (buttonIndex == null) {\n throw new IllegalArgumentException(\"Layout code not found: \" + code);\n }\n return buttonIndex;\n }\n\n //endregion\n}\n"},"new_file":{"kind":"string","value":"app/src/org/commcare/android/adapters/HomeScreenAdapter.java"},"old_contents":{"kind":"string","value":"package org.commcare.android.adapters;\n\nimport android.content.Context;\nimport android.util.Log;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\n\nimport org.commcare.android.view.SquareButtonWithNotification;\nimport org.commcare.dalvik.R;\n\nimport java.util.HashMap;\nimport java.util.LinkedList;\n\n/**\n * Sets up home screen buttons and gives accessors for setting their visibility and listeners\n * Created by dancluna on 3/19/15.\n */\npublic class HomeScreenAdapter extends BaseAdapter {\n //region Buttons\n\n static final int[] buttonsResources = new int[]{\n R.layout.home_start_button,\n R.layout.home_savedforms_button,\n R.layout.home_incompleteforms_button,\n R.layout.home_sync_button,\n R.layout.home_disconnect_button,\n };\n\n static final HashMap buttonsIDsToResources = new HashMap() {{\n put(R.id.home_start_sqbn,R.layout.home_start_button);\n put(R.id.home_savedforms_sqbn,R.layout.home_savedforms_button);\n put(R.id.home_sync_sqbn,R.layout.home_sync_button);\n put(R.id.home_disconnect_sqbn,R.layout.home_disconnect_button);\n put(R.id.home_incompleteforms_sqbn,R.layout.home_incompleteforms_button);\n }};\n\n //endregion\n\n //region Private variables\n\n final View.OnClickListener[] buttonListeners = new View.OnClickListener[buttonsResources.length];\n\n final SquareButtonWithNotification[] buttons = new SquareButtonWithNotification[buttonsResources.length];\n\n private Context context;\n\n private boolean[] hiddenButtons = new boolean[buttonsResources.length];\n private boolean isInitialized = false;\n\n private LinkedList visibleButtons;\n\n //endregion\n\n //region Constructors\n\n public HomeScreenAdapter(Context c) { this.context = c; }\n\n //endregion\n\n //region Public API\n\n /**\n * Sets the onClickListener for the given button\n * @param resourceCode Android resource code (R.id.$button or R.layout.$button)\n * @param lookupID If set, will search for the button with the given R.id\n * @param listener OnClickListener for the button\n */\n public void setOnClickListenerForButton(int resourceCode, boolean lookupID, View.OnClickListener listener){\n int buttonIndex = getButtonIndex(resourceCode, lookupID);\n buttonListeners[buttonIndex] = listener;\n SquareButtonWithNotification button = (SquareButtonWithNotification) getItem(buttonIndex);\n if(button != null){\n button.setOnClickListener(listener);\n }\n }\n\n public SquareButtonWithNotification getButton(int resourceCode, boolean lookupID){\n return buttons[getButtonIndex(resourceCode, lookupID)];\n }\n\n public void setNotificationTextForButton(int resourceCode, boolean lookupID, String notificationText) {\n SquareButtonWithNotification button = getButton(resourceCode, lookupID);\n if (button != null) {\n button.setNotificationText(notificationText);\n notifyDataSetChanged();\n }\n }\n\n @Override\n public int getCount() {\n// return buttonsResources.length;\n return visibleButtons == null ? buttonsResources.length : visibleButtons.size();\n }\n\n @Override\n public Object getItem(int position) {\n return buttons[position];\n }\n\n @Override\n public long getItemId(int position) {\n return buttonsResources[position];\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if(!isInitialized){\n visibleButtons = new LinkedList();\n Log.i(\"HomeScrnAdpt\",\"Creating all buttons because got a null in position \" + position);\n for (int i = 0; i < buttons.length; i++) {\n if (buttons[i] != null) continue;\n SquareButtonWithNotification button = (SquareButtonWithNotification) LayoutInflater.from(context)\n .inflate(buttonsResources[i], parent, false);\n buttons[i] = button;\n Log.i(\"HomeScrnAdpt\",\"Added button \" + button + \"to position \" + i);\n\n View.OnClickListener listener = buttonListeners[i];\n // creating now, but set a clickListener before, so we'll add it to this button...\n if(listener != null) {\n button.setOnClickListener(listener);\n Log.i(\"HomeScrnAdpt\",\"Added onClickListener \" + listener + \" to button in position \" + i);\n }\n if(!hiddenButtons[i]) visibleButtons.add(button);\n }\n isInitialized = true;\n }\n if(position < 0 || position >= getCount()) return null;\n if(convertView != null) {\n return convertView;\n } else {\n SquareButtonWithNotification btn = visibleButtons.get(position);\n\n if(btn == null) {\n Log.i(\"HomeScrnAdpt\",\"Unexpected null button\");\n }\n\n return btn;\n }\n }\n\n /**\n * Sets visibility for the button with the given resource code\n * @param resourceCode Android resource code (R.id.$button or R.layout.$button)\n * @param lookupID If set, will search for the button with the given R.id\n * @param isButtonHidden Button visibility state (true for hidden, false for visible)\n */\n public void setButtonVisibility(int resourceCode, boolean lookupID, boolean isButtonHidden){\n int index = getButtonIndex(resourceCode, lookupID);\n boolean toggled = isButtonHidden ^ hiddenButtons[index]; // checking if the button visibility was changed in this call\n hiddenButtons[index] = isButtonHidden;\n if (visibleButtons != null) {\n if(!toggled) return; // if the visibility was not changed, we don't need to do anything\n if(isButtonHidden) { // if the visibility was changed, we add/remove the button from the visible buttons' list\n visibleButtons.remove(buttons[index]);\n } else {\n visibleButtons.add(index, buttons[index]);\n }\n }\n }\n\n //endregion\n\n //region Private methods\n\n\n\n /**\n * Returns the index of the button with the given resource code. If lookupID is set, will search for the button with the given R.id; if not, will search for the button with the given R.layout code.\n * @param resourceCode\n * @param lookupID\n * @return\n * @throws java.lang.IllegalArgumentException If the given resourceCode is not found\n */\n private int getButtonIndex(int resourceCode, boolean lookupID){\n int code = resourceCode;\n // if lookupID is set, we are mapping from an int in R.id to one in R.layout\n if(lookupID){\n Integer layoutCode = buttonsIDsToResources.get(resourceCode);\n if(layoutCode == null) throw new IllegalArgumentException(\"ID code not found: \" + resourceCode);\n code = layoutCode;\n }\n Integer buttonIndex = null;\n for (int i = 0; i < buttonsResources.length; i++) {\n if(code == buttonsResources[i]){\n buttonIndex = i;\n break;\n }\n }\n if(buttonIndex == null) throw new IllegalArgumentException(\"Layout code not found: \" + code);\n return buttonIndex;\n }\n\n //endregion\n}\n"},"message":{"kind":"string","value":"Code review: removing complex logic from HomeScreenAdapter\n"},"old_file":{"kind":"string","value":"app/src/org/commcare/android/adapters/HomeScreenAdapter.java"},"subject":{"kind":"string","value":"Code review: removing complex logic from HomeScreenAdapter"}}},{"rowIdx":145822,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"075922b90f5b0dee9ac5c5f7060b5cc54078f14a"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"mintern/gson"},"new_contents":{"kind":"string","value":"/*\n * Copyright (C) 2008 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.gson;\n\nimport com.google.gson.internal.LruCache;\nimport com.google.gson.internal.Types;\nimport com.google.gson.internal.UnsafeAllocator;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Type;\n\n/**\n * This class contains a mapping of all the application specific\n * {@link InstanceCreator} instances. Registering an {@link InstanceCreator}\n * with this class will override the default object creation that is defined\n * by the ObjectConstructor that this class is wrapping. Using this class\n * with the JSON framework provides the application with \"pluggable\" modules\n * to customize framework to suit the application's needs.\n *\n * @author Joel Leitch\n */\nfinal class MappedObjectConstructor implements ObjectConstructor {\n private static final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();\n\n private static final LruCache, Constructor>> noArgsConstructorsCache =\n new LruCache, Constructor>>(500);\n private final ParameterizedTypeHandlerMap> instanceCreatorMap;\n /**\n * We need a special null value to indicate that the class does not have a no-args constructor.\n * This helps avoid using reflection over and over again for such classes. For convenience, we\n * use the no-args constructor of this class itself since this class would never be\n * deserialized using Gson.\n */\n private static final Constructor NULL_VALUE =\n getNoArgsConstructorUsingReflection(MappedObjectConstructor.class);\n \n @SuppressWarnings(\"unused\")\n private MappedObjectConstructor() {\n this(null);\n }\n\n public MappedObjectConstructor(\n ParameterizedTypeHandlerMap> instanceCreators) {\n instanceCreatorMap = instanceCreators;\n }\n\n @SuppressWarnings(\"unchecked\")\n public T construct(Type typeOfT) {\n InstanceCreator creator = (InstanceCreator) instanceCreatorMap.getHandlerFor(typeOfT);\n if (creator != null) {\n return creator.createInstance(typeOfT);\n }\n return (T) constructWithNoArgConstructor(typeOfT);\n }\n\n public Object constructArray(Type type, int length) {\n return Array.newInstance(Types.getRawType(type), length);\n }\n\n @SuppressWarnings({\"unchecked\", \"cast\"})\n private T constructWithNoArgConstructor(Type typeOfT) {\n try {\n Class clazz = (Class) Types.getRawType(typeOfT);\n Constructor constructor = getNoArgsConstructor(clazz);\n return constructor == null\n ? unsafeAllocator.newInstance(clazz)\n : constructor.newInstance();\n } catch (Exception e) {\n throw new RuntimeException((\"Unable to invoke no-args constructor for \" + typeOfT + \". \"\n + \"Register an InstanceCreator with Gson for this type may fix this problem.\"), e);\n }\n }\n\n private Constructor getNoArgsConstructor(Class clazz) {\n @SuppressWarnings(\"unchecked\")\n Constructor constructor = (Constructor)noArgsConstructorsCache.getElement(clazz);\n if (constructor == NULL_VALUE) {\n return null;\n }\n if (constructor == null) {\n constructor = getNoArgsConstructorUsingReflection(clazz);\n noArgsConstructorsCache.addElement(clazz, constructor);\n }\n return constructor == NULL_VALUE ? null : constructor;\n }\n\n @SuppressWarnings(\"unchecked\")\n private static Constructor getNoArgsConstructorUsingReflection(Class clazz) {\n try {\n Constructor constructor = clazz.getDeclaredConstructor();\n constructor.setAccessible(true);\n return constructor;\n } catch (Exception e) {\n return (Constructor) NULL_VALUE;\n }\n }\n\n @Override\n public String toString() {\n return instanceCreatorMap.toString();\n }\n}\n"},"new_file":{"kind":"string","value":"src/main/java/com/google/gson/MappedObjectConstructor.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (C) 2008 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.gson;\n\nimport com.google.gson.internal.Types;\nimport com.google.gson.internal.UnsafeAllocator;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Type;\n\n/**\n * This class contains a mapping of all the application specific\n * {@link InstanceCreator} instances. Registering an {@link InstanceCreator}\n * with this class will override the default object creation that is defined\n * by the ObjectConstructor that this class is wrapping. Using this class\n * with the JSON framework provides the application with \"pluggable\" modules\n * to customize framework to suit the application's needs.\n *\n * @author Joel Leitch\n */\nfinal class MappedObjectConstructor implements ObjectConstructor {\n private static final UnsafeAllocator unsafeAllocator = UnsafeAllocator.create();\n\n private final ParameterizedTypeHandlerMap> instanceCreatorMap;\n\n public MappedObjectConstructor(\n ParameterizedTypeHandlerMap> instanceCreators) {\n instanceCreatorMap = instanceCreators;\n }\n\n @SuppressWarnings(\"unchecked\")\n public T construct(Type typeOfT) {\n InstanceCreator creator = (InstanceCreator) instanceCreatorMap.getHandlerFor(typeOfT);\n if (creator != null) {\n return creator.createInstance(typeOfT);\n }\n return (T) constructWithNoArgConstructor(typeOfT);\n }\n\n public Object constructArray(Type type, int length) {\n return Array.newInstance(Types.getRawType(type), length);\n }\n\n @SuppressWarnings({\"unchecked\", \"cast\"})\n private T constructWithNoArgConstructor(Type typeOfT) {\n try {\n Class clazz = (Class) Types.getRawType(typeOfT);\n Constructor constructor = getNoArgsConstructor(clazz);\n return constructor == null\n ? unsafeAllocator.newInstance(clazz)\n : constructor.newInstance();\n } catch (Exception e) {\n throw new RuntimeException((\"Unable to invoke no-args constructor for \" + typeOfT + \". \"\n + \"Register an InstanceCreator with Gson for this type may fix this problem.\"), e);\n }\n }\n\n private Constructor getNoArgsConstructor(Class clazz) {\n try {\n Constructor declaredConstructor = clazz.getDeclaredConstructor();\n declaredConstructor.setAccessible(true);\n return declaredConstructor;\n } catch (Exception e) {\n return null;\n }\n }\n\n @Override\n public String toString() {\n return instanceCreatorMap.toString();\n }\n}\n"},"message":{"kind":"string","value":"Added a cache for no-args constructors to avoid expensive reflection everytime an object needs to be instantiated.\n\ngit-svn-id: 7b8be7b2f8bf58e8147c910303b95fa2b8d9948f@748 2534bb62-2c4b-0410-85e8-b5006b95c4ae\n"},"old_file":{"kind":"string","value":"src/main/java/com/google/gson/MappedObjectConstructor.java"},"subject":{"kind":"string","value":"Added a cache for no-args constructors to avoid expensive reflection everytime an object needs to be instantiated."}}},{"rowIdx":145823,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-2-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"8f562030388957c9807bbb71c792720d4a6660e0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"JayH5/jbox2d,jbox2d/jbox2d,JayH5/jbox2d,wasimbeniwale/jbox2d,jbox2d/jbox2d,jbox2d/jbox2d,wasimbeniwale/jbox2d,wasimbeniwale/jbox2d,JayH5/jbox2d"},"new_contents":{"kind":"string","value":"/*\n * JBox2D - A Java Port of Erin Catto's Box2D\n * \n * JBox2D homepage: http://jbox2d.sourceforge.net/\n * Box2D homepage: http://www.box2d.org\n * \n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n * \n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n * \n * 1. The origin of this software must not be misrepresented; you must not\n * claim that you wrote the original software. If you use this software\n * in a product, an acknowledgment in the product documentation would be\n * appreciated but is not required.\n * 2. Altered source versions must be plainly marked as such, and must not be\n * misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n */\n\npackage org.jbox2d.dynamics.contacts;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jbox2d.collision.ContactID;\nimport org.jbox2d.collision.Manifold;\nimport org.jbox2d.collision.ManifoldPoint;\nimport org.jbox2d.collision.shapes.CircleShape;\nimport org.jbox2d.collision.shapes.PolygonShape;\nimport org.jbox2d.collision.shapes.Shape;\nimport org.jbox2d.collision.shapes.ShapeType;\nimport org.jbox2d.common.Vec2;\nimport org.jbox2d.dynamics.Body;\nimport org.jbox2d.dynamics.ContactListener;\nimport org.jbox2d.pooling.SingletonPool;\nimport org.jbox2d.pooling.TLContactPoint;\nimport org.jbox2d.pooling.TLManifold;\nimport org.jbox2d.pooling.TLVec2;\nimport org.jbox2d.pooling.arrays.BooleanArray;\n\n//Updated to rev 144 of b2PolyAndCircleContact.h/cpp\nclass PolyAndCircleContact extends Contact implements ContactCreateFcn {\n\n\tpublic final Manifold m_manifold;\n\tpublic final ArrayList manifoldList = new ArrayList();\n\n\tpublic PolyAndCircleContact(final Shape s1, final Shape s2) {\n\t\tsuper(s1, s2);\n\t\tassert (m_shape1.getType() == ShapeType.POLYGON_SHAPE);\n\t\tassert (m_shape2.getType() == ShapeType.CIRCLE_SHAPE);\n\t\tm_manifold = new Manifold();\n\t\tmanifoldList.add(m_manifold);\n\t\tm_manifoldCount = 0;\n\t\t// These should not be necessary, manifold was\n\t\t// just created...\n\t\t//m_manifold.points[0].normalImpulse = 0.0f;\n\t\t//m_manifold.points[0].tangentImpulse = 0.0f;\n\t}\n\n\tpublic PolyAndCircleContact() {\n\t\tsuper();\n\t\tm_manifold = new Manifold();\n\t\tm_manifoldCount = 0;\n\t}\n\n\t@Override\n\tpublic Contact clone() {\n\t\tfinal PolyAndCircleContact newC = new PolyAndCircleContact(this.m_shape1,\n\t\t this.m_shape2);\n\t\tnewC.m_manifold.set(this.m_manifold);\n\t\tnewC.m_manifoldCount = this.m_manifoldCount;\n\t\t// The parent world.\n\t\tnewC.m_world = this.m_world;\n\n\t\t// World pool and list pointers.\n\t\tnewC.m_prev = this.m_prev;\n\t\tnewC.m_next = this.m_next;\n\n\t\t// Nodes for connecting bodies.\n\t\tnewC.m_node1.set(m_node1);\n\t\tnewC.m_node2.set(m_node2);\n\n\t\t// Combined friction\n\t\tnewC.m_friction = this.m_friction;\n\t\tnewC.m_restitution = this.m_restitution;\n\n\t\tnewC.m_flags = this.m_flags;\n\t\treturn newC;\n\t}\n\n\tpublic Contact create(final Shape shape1, final Shape shape2) {\n\t\treturn new PolyAndCircleContact(shape1, shape2);\n\t}\n\n\t@Override\n\tpublic List getManifolds() {\n\t\treturn manifoldList;\n\t}\n\t\n\t// djm pooling\n\tprivate static final TLManifold tlm0 = new TLManifold();\n\tprivate static final TLVec2 tlV1 = new TLVec2();\n\tprivate static final TLContactPoint tlCp = new TLContactPoint();\n\tprivate static final BooleanArray tlPersisted = new BooleanArray();\n\t@Override\n\tpublic void evaluate(final ContactListener listener) {\n\t\tfinal Body b1 = m_shape1.getBody();\n\t\tfinal Body b2 = m_shape2.getBody();\n\t\t\n\t\tfinal Manifold m0 = tlm0.get();\n\t\tfinal Vec2 v1 = tlV1.get();\n\t\tfinal ContactPoint cp = tlCp.get();\n\n\t\tSingletonPool.getCollideCircle().collidePolygonAndCircle(m_manifold, (PolygonShape)m_shape1, b1.getMemberXForm(), (CircleShape)m_shape2, b2.getMemberXForm());\n\n\t\tfinal Boolean[] persisted = tlPersisted.get(2);\n\t\tpersisted[0] = false;\n\t\tpersisted[1] = false;\n\n\t\tcp.shape1 = m_shape1;\n\t\tcp.shape2 = m_shape2;\n\t\tcp.friction = m_friction;\n\t\tcp.restitution = m_restitution;\n\n\t\t// Match contact ids to facilitate warm starting.\n\t\tif (m_manifold.pointCount > 0) {\n\t\t\t// Match old contact ids to new contact ids and copy the\n\t\t\t// stored impulses to warm start the solver.\n\t\t\tfor (int i = 0; i < m_manifold.pointCount; ++i)\n\t\t\t{\n\t\t\t\tfinal ManifoldPoint mp = m_manifold.points[i];\n\t\t\t\tmp.normalImpulse = 0.0f;\n\t\t\t\tmp.tangentImpulse = 0.0f;\n\t\t\t\tboolean found = false;\n\t\t\t\tfinal ContactID id = mp.id;\n\n\t\t\t\tfor (int j = 0; j < m0.pointCount; ++j) {\n\t\t\t\t\tif (persisted[j] == true) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal ManifoldPoint mp0 = m0.points[j];\n\n\t\t\t\t\tif (mp0.id.isEqual(id)) {\n\t\t\t\t\t\tpersisted[j] = true;\n\t\t\t\t\t\tmp.normalImpulse = mp0.normalImpulse;\n\t\t\t\t\t\tmp.tangentImpulse = mp0.tangentImpulse;\n\n\t\t\t\t\t\t// A persistent point.\n\t\t\t\t\t\tfound = true;\n\n\t\t\t\t\t\t// Report persistent point.\n\t\t\t\t\t\tif (listener != null) {\n\t\t\t\t\t\t\tb1.getWorldLocationToOut(mp.localPoint1, cp.position);\n\t\t\t\t\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\t\t\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp.localPoint1, v1);\n\t\t\t\t\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\t\t\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp.localPoint2, cp.velocity);\n\t\t\t\t\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\t\t\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\t\t\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\t\t\t\t\tcp.separation = mp.separation;\n\t\t\t\t\t\t\tcp.id.set(id);\n\t\t\t\t\t\t\tlistener.persist(cp);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Report added point.\n\t\t\t\tif (found == false && listener != null) {\n\t\t\t\t\tb1.getWorldLocationToOut(mp.localPoint1, cp.position);\n\t\t\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp.localPoint1, v1);\n\t\t\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp.localPoint2, cp.velocity);\n\t\t\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\t\t\tcp.separation = mp.separation;\n\t\t\t\t\tcp.id.set(id);\n\t\t\t\t\tlistener.add(cp);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_manifoldCount = 1;\n\t\t} else {\n\t\t\tm_manifoldCount = 0;\n\t\t}\n\n\t\tif (listener == null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Report removed points.\n\t\tfor (int i = 0; i < m0.pointCount; ++i) {\n\t\t\tif (persisted[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfinal ManifoldPoint mp0 = m0.points[i];\n\t\t\tb1.getWorldLocationToOut(mp0.localPoint1, cp.position);\n\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp0.localPoint1, v1);\n\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp0.localPoint2, cp.velocity);\n\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\tcp.separation = mp0.separation;\n\t\t\tcp.id.set(mp0.id);\n\t\t\tlistener.remove(cp);\n\t\t}\n\t}\n}"},"new_file":{"kind":"string","value":"src/org/jbox2d/dynamics/contacts/PolyAndCircleContact.java"},"old_contents":{"kind":"string","value":"/*\n * JBox2D - A Java Port of Erin Catto's Box2D\n * \n * JBox2D homepage: http://jbox2d.sourceforge.net/\n * Box2D homepage: http://www.box2d.org\n * \n * This software is provided 'as-is', without any express or implied\n * warranty. In no event will the authors be held liable for any damages\n * arising from the use of this software.\n * \n * Permission is granted to anyone to use this software for any purpose,\n * including commercial applications, and to alter it and redistribute it\n * freely, subject to the following restrictions:\n * \n * 1. The origin of this software must not be misrepresented; you must not\n * claim that you wrote the original software. If you use this software\n * in a product, an acknowledgment in the product documentation would be\n * appreciated but is not required.\n * 2. Altered source versions must be plainly marked as such, and must not be\n * misrepresented as being the original software.\n * 3. This notice may not be removed or altered from any source distribution.\n */\n\npackage org.jbox2d.dynamics.contacts;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jbox2d.collision.ContactID;\nimport org.jbox2d.collision.Manifold;\nimport org.jbox2d.collision.ManifoldPoint;\nimport org.jbox2d.collision.shapes.CircleShape;\nimport org.jbox2d.collision.shapes.PolygonShape;\nimport org.jbox2d.collision.shapes.Shape;\nimport org.jbox2d.collision.shapes.ShapeType;\nimport org.jbox2d.common.Vec2;\nimport org.jbox2d.dynamics.Body;\nimport org.jbox2d.dynamics.ContactListener;\nimport org.jbox2d.pooling.SingletonPool;\nimport org.jbox2d.pooling.TLContactPoint;\nimport org.jbox2d.pooling.TLManifold;\nimport org.jbox2d.pooling.TLVec2;\nimport org.jbox2d.pooling.arrays.BooleanArray;\n\n//Updated to rev 144 of b2PolyAndCircleContact.h/cpp\nclass PolyAndCircleContact extends Contact implements ContactCreateFcn {\n\n\tpublic final Manifold m_manifold;\n\tpublic final ArrayList manifoldList = new ArrayList();\n\n\tpublic PolyAndCircleContact(final Shape s1, final Shape s2) {\n\t\tsuper(s1, s2);\n\t\tassert (m_shape1.getType() == ShapeType.POLYGON_SHAPE);\n\t\tassert (m_shape2.getType() == ShapeType.CIRCLE_SHAPE);\n\t\tm_manifold = new Manifold();\n\t\tmanifoldList.add(m_manifold);\n\t\tm_manifoldCount = 0;\n\t\t// These should not be necessary, manifold was\n\t\t// just created...\n\t\t//m_manifold.points[0].normalImpulse = 0.0f;\n\t\t//m_manifold.points[0].tangentImpulse = 0.0f;\n\t}\n\n\tpublic PolyAndCircleContact() {\n\t\tsuper();\n\t\tm_manifold = new Manifold();\n\t\tm_manifoldCount = 0;\n\t}\n\n\t@Override\n\tpublic Contact clone() {\n\t\tfinal PolyAndCircleContact newC = new PolyAndCircleContact(this.m_shape1,\n\t\t this.m_shape2);\n\t\tnewC.m_manifold.set(this.m_manifold);\n\t\tnewC.m_manifoldCount = this.m_manifoldCount;\n\t\t// The parent world.\n\t\tnewC.m_world = this.m_world;\n\n\t\t// World pool and list pointers.\n\t\tnewC.m_prev = this.m_prev;\n\t\tnewC.m_next = this.m_next;\n\n\t\t// Nodes for connecting bodies.\n\t\tnewC.m_node1.set(m_node1);\n\t\tnewC.m_node2.set(m_node2);\n\n\t\t// Combined friction\n\t\tnewC.m_friction = this.m_friction;\n\t\tnewC.m_restitution = this.m_restitution;\n\n\t\tnewC.m_flags = this.m_flags;\n\t\treturn newC;\n\t}\n\n\tpublic Contact create(final Shape shape1, final Shape shape2) {\n\t\treturn new PolyAndCircleContact(shape1, shape2);\n\t}\n\n\t@Override\n\tpublic List getManifolds() {\n\t\treturn manifoldList;\n\t}\n\t\n\t// djm pooling\n\tprivate static final TLManifold tlm0 = new TLManifold();\n\tprivate static final TLVec2 tlV1 = new TLVec2();\n\tprivate static final TLContactPoint tlCp = new TLContactPoint();\n\tprivate static final BooleanArray tlPersisted = new BooleanArray();\n\t@Override\n\tpublic void evaluate(final ContactListener listener) {\n\t\tfinal Body b1 = m_shape1.getBody();\n\t\tfinal Body b2 = m_shape2.getBody();\n\t\t\n\t\tfinal Manifold m0 = tlm0.get();\n\t\tfinal Vec2 v1 = tlV1.get();\n\t\tfinal ContactPoint cp = tlCp.get();\n\n\t\tSingletonPool.getCollideCircle().collidePolygonAndCircle(m_manifold, (PolygonShape)m_shape1, b1.getMemberXForm(), (CircleShape)m_shape2, b2.getMemberXForm());\n\n\t\tfinal Boolean[] persisted = tlPersisted.get(2);\n\t\tpersisted[0] = false;\n\t\tpersisted[1] = false;\n\n\t\tcp.shape1 = m_shape1;\n\t\tcp.shape2 = m_shape2;\n\t\tcp.friction = m_friction;\n\t\tcp.restitution = m_restitution;\n\n\t\t// Match contact ids to facilitate warm starting.\n\t\tif (m_manifold.pointCount > 0) {\n\t\t\t// Match old contact ids to new contact ids and copy the\n\t\t\t// stored impulses to warm start the solver.\n\t\t\tfor (int i = 0; i < m_manifold.pointCount; ++i)\n\t\t\t{\n\t\t\t\tfinal ManifoldPoint mp = m_manifold.points[i];\n\t\t\t\tmp.normalImpulse = 0.0f;\n\t\t\t\tmp.tangentImpulse = 0.0f;\n\t\t\t\tboolean found = false;\n\t\t\t\tfinal ContactID id = new ContactID(mp.id);\n\n\t\t\t\tfor (int j = 0; j < m0.pointCount; ++j) {\n\t\t\t\t\tif (persisted[j] == true) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfinal ManifoldPoint mp0 = m0.points[j];\n\n\t\t\t\t\tif (mp0.id.isEqual(id)) {\n\t\t\t\t\t\tpersisted[j] = true;\n\t\t\t\t\t\tmp.normalImpulse = mp0.normalImpulse;\n\t\t\t\t\t\tmp.tangentImpulse = mp0.tangentImpulse;\n\n\t\t\t\t\t\t// A persistent point.\n\t\t\t\t\t\tfound = true;\n\n\t\t\t\t\t\t// Report persistent point.\n\t\t\t\t\t\tif (listener != null) {\n\t\t\t\t\t\t\tb1.getWorldLocationToOut(mp.localPoint1, cp.position);\n\t\t\t\t\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\t\t\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp.localPoint1, v1);\n\t\t\t\t\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\t\t\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp.localPoint2, cp.velocity);\n\t\t\t\t\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\t\t\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\t\t\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\t\t\t\t\tcp.separation = mp.separation;\n\t\t\t\t\t\t\tcp.id.set(id);\n\t\t\t\t\t\t\tlistener.persist(cp);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Report added point.\n\t\t\t\tif (found == false && listener != null) {\n\t\t\t\t\tb1.getWorldLocationToOut(mp.localPoint1, cp.position);\n\t\t\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp.localPoint1, v1);\n\t\t\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp.localPoint2, cp.velocity);\n\t\t\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\t\t\tcp.separation = mp.separation;\n\t\t\t\t\tcp.id.set(id);\n\t\t\t\t\tlistener.add(cp);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_manifoldCount = 1;\n\t\t} else {\n\t\t\tm_manifoldCount = 0;\n\t\t}\n\n\t\tif (listener == null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Report removed points.\n\t\tfor (int i = 0; i < m0.pointCount; ++i) {\n\t\t\tif (persisted[i]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfinal ManifoldPoint mp0 = m0.points[i];\n\t\t\tb1.getWorldLocationToOut(mp0.localPoint1, cp.position);\n\t\t\t//Vec2 v1 = b1.getLinearVelocityFromLocalPoint(mp.localPoint1);\n\t\t\tb1.getLinearVelocityFromLocalPointToOut(mp0.localPoint1, v1);\n\t\t\t//Vec2 v2 = b2.getLinearVelocityFromLocalPoint(mp.localPoint2);\n\t\t\tb2.getLinearVelocityFromLocalPointToOut(mp0.localPoint2, cp.velocity);\n\t\t\t//cp.velocity = v2.sub(v1);\n\t\t\tcp.velocity.subLocal(v1);\n\n\t\t\tcp.normal.set(m_manifold.normal);\n\t\t\tcp.separation = mp0.separation;\n\t\t\tcp.id.set(mp0.id);\n\t\t\tlistener.remove(cp);\n\t\t}\n\t}\n}"},"message":{"kind":"string","value":"optimization\n"},"old_file":{"kind":"string","value":"src/org/jbox2d/dynamics/contacts/PolyAndCircleContact.java"},"subject":{"kind":"string","value":"optimization"}}},{"rowIdx":145824,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"bsd-3-clause"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"addf7eda0f2dc7be83bde8f2daecdea302db87da"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"arjunbm13/stevia,persado/stevia,persado/stevia,ptsiakos77/stevia,arjunbm13/stevia,ptsiakos77/stevia,persado/stevia,arjunbm13/stevia,ptsiakos77/stevia,ptsiakos77/stevia,arjunbm13/stevia,persado/stevia"},"new_contents":{"kind":"string","value":""},"new_file":{"kind":"string","value":"src/main/java/com/persado/oss/quality/stevia/selenium/core/controllers/AppiumWebController.java"},"old_contents":{"kind":"string","value":"package com.persado.oss.quality.stevia.selenium.core.controllers;\n\nimport com.persado.oss.quality.stevia.network.http.HttpCookie;\nimport com.persado.oss.quality.stevia.selenium.core.WebController;\nimport com.persado.oss.quality.stevia.selenium.core.controllers.commonapi.KeyInfo;\nimport org.openqa.selenium.Point;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.interactions.Actions;\n\nimport java.io.IOException;\nimport java.util.List;\n\n/**\n * Created by gkogketsof on 12/10/13.\n */\npublic class AppiumWebController extends WebControllerBase implements WebController {\n private WebDriver driver;\n @Override\n public void enableActionsLogging() {\n\n }\n\n @Override\n public void disableActionsLogging() {\n\n }\n\n @Override\n public void close() {\n\n }\n\n @Override\n public void quit() {\n\n }\n\n @Override\n public WebElement waitForElement(String locator) {\n return null;\n }\n\n @Override\n public WebElement waitForElement(String locator, long waitSeconds) {\n return null;\n }\n\n @Override\n public void waitForElementInvisibility(String locator) {\n\n }\n\n @Override\n public void waitForElementInvisibility(String locator, long waitSeconds) {\n\n }\n\n @Override\n public WebElement waitForElementPresence(String locator) {\n return null;\n }\n\n @Override\n public WebElement waitForElementPresence(String locator, long waitSeconds) {\n return null;\n }\n\n @Override\n public List findElements(String locator) {\n return null;\n }\n\n @Override\n public void input(String locator, String value) {\n\n }\n\n @Override\n public void press(String locator) {\n\n }\n\n @Override\n public void pressAndWaitForPageToLoad(String locator) {\n\n }\n\n @Override\n public void pressAndWaitForElement(String pressLocator, String elementToWaitLocator, long waitSeconds) {\n\n }\n\n @Override\n public void pressAndWaitForElement(String pressLocator, String elementToWaitLocator) {\n\n }\n\n @Override\n public void pressAndClickOkInAlert(String locator) {\n\n }\n\n @Override\n public void pressAndClickOkInAlertNoPageLoad(String locator) {\n\n }\n\n @Override\n public void pressAndClickCancelInAlert(String locator) {\n\n }\n\n @Override\n public void select(String locator, String option) {\n\n }\n\n @Override\n public void selectByValue(String locator, String value) {\n\n }\n\n @Override\n public void multiSelectAdd(String locator, String option) {\n\n }\n\n @Override\n public Object executeJavascript(String js, Object... args) {\n return null;\n }\n\n @Override\n public void waitForCondition(String jscondition) {\n\n }\n\n @Override\n public void waitForCondition(String jscondition, long waitSeconds) {\n\n }\n\n @Override\n public void clear(String locator) {\n\n }\n\n @Override\n public Actions getBuilder() {\n return null;\n }\n\n @Override\n public void mouseOver(String locator) {\n\n }\n\n @Override\n public void mouseUp(String locator) {\n\n }\n\n @Override\n public void mouseDown(String locator) {\n\n }\n\n @Override\n public void click(String locator) {\n\n }\n\n @Override\n public void doubleClick(String locator) {\n\n }\n\n @Override\n public void highlight(String locator) {\n\n }\n\n @Override\n public void highlight(String locator, String color) {\n\n }\n\n @Override\n public void takeScreenShot() throws IOException {\n\n }\n\n @Override\n public String getText(String locator) {\n return null;\n }\n\n @Override\n public void getFocus(String locator) {\n\n }\n\n @Override\n public String getSelectedOption(String locator) {\n return null;\n }\n\n @Override\n public List getSelectedOptions(String locator) {\n return null;\n }\n\n @Override\n public String getInputValue(String locator) {\n return null;\n }\n\n @Override\n public boolean isAlertPresent() {\n return false;\n }\n\n @Override\n public boolean isTextPresent(String value) {\n return false;\n }\n\n @Override\n public boolean isTextNotPresent(String value) {\n return false;\n }\n\n @Override\n public boolean isComponentEditable(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentDisabled(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentPresent(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentPresent(String locator, long seconds) {\n return false;\n }\n\n @Override\n public boolean isComponentNotPresent(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentVisible(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentVisible(String locator, long seconds) {\n return false;\n }\n\n @Override\n public boolean isComponentNotVisible(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentNotVisible(String locator, long seconds) {\n return false;\n }\n\n @Override\n public boolean isComponentSelected(String locator) {\n return false;\n }\n\n @Override\n public boolean isComponentNotSelected(String locator) {\n return false;\n }\n\n @Override\n public void pressLinkName(String linkName) {\n\n }\n\n @Override\n public void pressLinkNameAndWaitForPageToLoad(String linkName) {\n\n }\n\n @Override\n public void pressLinkNameAndClickOkInAlert(String linkName) {\n\n }\n\n @Override\n public void pressLinkNameAndClickOkInAlertNoPageLoad(String linkName) {\n\n }\n\n @Override\n public void pressLinkNameAndClickCancelInAlert(String linkName) {\n\n }\n\n @Override\n public void typeKeys(String locator, String value) {\n\n }\n\n @Override\n public void keyDown(String locator, KeyInfo thekey) {\n\n }\n\n @Override\n public void keyUp(String locator, KeyInfo thekey) {\n\n }\n\n @Override\n public void keyPress(String locator, KeyInfo thekey) {\n\n }\n\n @Override\n public void keyDown(KeyInfo thekey) {\n\n }\n\n @Override\n public void keyUp(KeyInfo thekey) {\n\n }\n\n @Override\n public void keyPress(KeyInfo thekey) {\n\n }\n\n @Override\n public void clickOkInAlert() {\n\n }\n\n @Override\n public void promptInputPressOK(String inputMessage) {\n\n }\n\n @Override\n public void promptInputPressCancel(String inputMessage) {\n\n }\n\n @Override\n public void clickCancelInAlert() {\n\n }\n\n @Override\n public void navigate(String url) {\n\n }\n\n @Override\n public void refresh() {\n\n }\n\n @Override\n public String getTableElementRowPosition(String locator, String elementName) {\n return null;\n }\n\n @Override\n public int getNumberOfTotalRows(String locator) {\n return 0;\n }\n\n @Override\n public int getNumberOfTotalColumns(String locator) {\n return 0;\n }\n\n @Override\n public List> getTableInfoAsList(String locator) {\n return null;\n }\n\n @Override\n public String getTableElementTextUnderHeader(String locator, String elementName, String headerName) {\n return null;\n }\n\n @Override\n public String getTableElementTextForRowAndColumn(String locator, String row, String column) {\n return null;\n }\n\n @Override\n public String getTableHeaderPosition(String locator, String headerName) {\n return null;\n }\n\n @Override\n public String getTableElementColumnPosition(String locator, String elementName) {\n return null;\n }\n\n @Override\n public List getTableRecordsUnderHeader(String locator, String headerName) {\n return null;\n }\n\n @Override\n public String[][] getTableElements2DArray(String locator) {\n return new String[0][];\n }\n\n @Override\n public String getTableElementSpecificHeaderLocator(String locator, String elementName, String headerName) {\n return null;\n }\n\n @Override\n public String getTableElementSpecificRowAndColumnLocator(String locator, String row, String column) {\n return null;\n }\n\n @Override\n public String getAttributeValue(String locator, String attribute) {\n return null;\n }\n\n @Override\n public HttpCookie getCookieByName(String name) {\n return null;\n }\n\n @Override\n public List getAllCookies() {\n return null;\n }\n\n @Override\n public void dragAndDrop(String locatorFrom, String locatorTo) {\n\n }\n\n @Override\n public void switchToLatestWindow() {\n\n }\n\n @Override\n public String getAlertText() {\n return null;\n }\n\n @Override\n public List getAllListOptions(String locator) {\n return null;\n }\n\n @Override\n public void selectFrame(String frameID) {\n\n }\n\n @Override\n public void selectFrameMain() {\n\n }\n\n @Override\n public void maximizeWindow() {\n\n }\n\n @Override\n public int getNumberOfElementsMatchLocator(String locator) {\n return 0;\n }\n\n @Override\n public void moveToElement(String locator, int x, int y) {\n\n }\n\n @Override\n public void moveToElement(String locator) {\n\n }\n\n @Override\n public void moveByOffset(int xOffset, int yOffset) {\n\n }\n\n @Override\n public void waitForAjaxComplete(long milliseconds) {\n\n }\n\n @Override\n public String getCurrentUrl() {\n return null;\n }\n\n @Override\n public void dragAndDrop(String locatorFrom, int xOffset, int yOffset) {\n\n }\n\n @Override\n public Point getElementPosition(String locator) {\n return null;\n }\n\n @Override\n public String getPageSource() {\n return null;\n }\n\n public void setDriver(WebDriver driver) {\n this.driver = driver;\n }\n}\n"},"message":{"kind":"string","value":"RMV: wrong push\n"},"old_file":{"kind":"string","value":"src/main/java/com/persado/oss/quality/stevia/selenium/core/controllers/AppiumWebController.java"},"subject":{"kind":"string","value":"RMV: wrong push"}}},{"rowIdx":145825,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"isc"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"96312ae95bf106f9dfb8da38f6314f5e489894ba"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"garyttierney/apollo,ryleykimmel/apollo,garyttierney/apollo,apollo-rsps/apollo,apollo-rsps/apollo,SJ19/apollo,Major-/apollo,LegendSky/apollo,Major-/apollo,SJ19/apollo,apollo-rsps/apollo,LegendSky/apollo,ryleykimmel/apollo"},"new_contents":{"kind":"string","value":"package org.apollo.game.model;\n\nimport java.io.BufferedInputStream;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.logging.Logger;\n\nimport org.apollo.Service;\nimport org.apollo.fs.IndexedFileSystem;\nimport org.apollo.fs.decoder.ItemDefinitionDecoder;\nimport org.apollo.fs.decoder.NpcDefinitionDecoder;\nimport org.apollo.fs.decoder.ObjectDefinitionDecoder;\nimport org.apollo.fs.decoder.StaticObjectDecoder;\nimport org.apollo.game.command.CommandDispatcher;\nimport org.apollo.game.login.LoginDispatcher;\nimport org.apollo.game.login.LogoutDispatcher;\nimport org.apollo.game.model.def.EquipmentDefinition;\nimport org.apollo.game.model.def.ItemDefinition;\nimport org.apollo.game.model.def.NpcDefinition;\nimport org.apollo.game.model.def.ObjectDefinition;\nimport org.apollo.game.model.obj.GameObject;\nimport org.apollo.game.model.sector.Sector;\nimport org.apollo.game.model.sector.SectorCoordinates;\nimport org.apollo.game.model.sector.SectorRepository;\nimport org.apollo.game.scheduling.ScheduledTask;\nimport org.apollo.game.scheduling.Scheduler;\nimport org.apollo.io.EquipmentDefinitionParser;\nimport org.apollo.util.MobRepository;\nimport org.apollo.util.NameUtil;\nimport org.apollo.util.plugin.PluginManager;\n\n/**\n * The world class is a singleton which contains objects like the {@link MobRepository} for players and NPCs. It should\n * only contain things relevant to the in-game world and not classes which deal with I/O and such (these may be better\n * off inside some custom {@link Service} or other code, however, the circumstances are rare).\n * \n * @author Graham\n */\npublic final class World {\n\n\t/**\n\t * Represents the different status codes for registering a player.\n\t * \n\t * @author Graham\n\t */\n\tpublic enum RegistrationStatus {\n\n\t\t/**\n\t\t * Indicates that the player is already online.\n\t\t */\n\t\tALREADY_ONLINE,\n\n\t\t/**\n\t\t * Indicates that the player was registered successfully.\n\t\t */\n\t\tOK,\n\n\t\t/**\n\t\t * Indicates the world is full.\n\t\t */\n\t\tWORLD_FULL;\n\n\t}\n\n\t/**\n\t * The logger for this class.\n\t */\n\tprivate static final Logger logger = Logger.getLogger(World.class.getName());\n\n\t/**\n\t * The world.\n\t */\n\tprivate static final World world = new World();\n\n\t/**\n\t * Gets the world.\n\t * \n\t * @return The world.\n\t */\n\tpublic static World getWorld() {\n\t\treturn world;\n\t}\n\n\t/**\n\t * The command dispatcher.\n\t */\n\tprivate final CommandDispatcher commandDispatcher = new CommandDispatcher();\n\n\t/**\n\t * The login dispatcher.\n\t */\n\tprivate final LoginDispatcher loginDispatcher = new LoginDispatcher();\n\n\t/**\n\t * The logout dispatcher.\n\t */\n\tprivate final LogoutDispatcher logoutDispatcher = new LogoutDispatcher();\n\n\t/**\n\t * The {@link MobRepository} of {@link Npc}s.\n\t */\n\tprivate final MobRepository npcRepository = new MobRepository<>(WorldConstants.MAXIMUM_NPCS);\n\n\t/**\n\t * The {@link MobRepository} of {@link Player}s.\n\t */\n\tprivate final MobRepository playerRepository = new MobRepository<>(WorldConstants.MAXIMUM_PLAYERS);\n\n\t/**\n\t * A {@link Map} of player usernames and the player objects.\n\t */\n\tprivate final Map players = new HashMap<>();\n\n\t/**\n\t * The {@link PluginManager}. TODO: better place than here!!\n\t */\n\tprivate PluginManager pluginManager;\n\n\t/**\n\t * The release number (i.e. version) of this world.\n\t */\n\tprivate int releaseNumber;\n\n\t/**\n\t * The scheduler.\n\t */\n\tprivate final Scheduler scheduler = new Scheduler();\n\n\t/**\n\t * This world's {@link SectorRepository}.\n\t */\n\tprivate final SectorRepository sectorRepository = new SectorRepository(false);\n\n\t/**\n\t * Creates the world.\n\t */\n\tprivate World() {\n\n\t}\n\n\t/**\n\t * Gets the command dispatcher.\n\t * \n\t * @return The command dispatcher.\n\t */\n\tpublic CommandDispatcher getCommandDispatcher() {\n\t\treturn commandDispatcher;\n\t}\n\n\t/**\n\t * Gets the {@link LoginDispatcher}.\n\t * \n\t * @return The dispatcher.\n\t */\n\tpublic LoginDispatcher getLoginDispatcher() {\n\t\treturn loginDispatcher;\n\t}\n\n\t/**\n\t * Gets the {@link LogoutDispatcher}.\n\t * \n\t * @return The dispatcher.\n\t */\n\tpublic LogoutDispatcher getLogoutDispatcher() {\n\t\treturn logoutDispatcher;\n\t}\n\n\t/**\n\t * Gets the npc repository.\n\t * \n\t * @return The npc repository.\n\t */\n\tpublic MobRepository getNpcRepository() {\n\t\treturn npcRepository;\n\t}\n\n\t/**\n\t * Gets the {@link Player} with the specified username. Note that this will return {@code null} if the player is\n\t * offline.\n\t * \n\t * @param username The username.\n\t * @return The player.\n\t */\n\tpublic Player getPlayer(String username) {\n\t\treturn players.get(NameUtil.encodeBase37(username.toLowerCase()));\n\t}\n\n\t/**\n\t * Gets the player repository.\n\t * \n\t * @return The player repository.\n\t */\n\tpublic MobRepository getPlayerRepository() {\n\t\treturn playerRepository;\n\t}\n\n\t/**\n\t * Gets the plugin manager. TODO should this be here?\n\t * \n\t * @return The plugin manager.\n\t */\n\tpublic PluginManager getPluginManager() {\n\t\treturn pluginManager;\n\t}\n\n\t/**\n\t * Gets the release number of this world.\n\t * \n\t * @return The release number.\n\t */\n\tpublic int getReleaseNumber() {\n\t\treturn releaseNumber;\n\t}\n\n\t/**\n\t * Gets this world's {@link SectorRepository}.\n\t * \n\t * @return The sector repository.\n\t */\n\tpublic SectorRepository getSectorRepository() {\n\t\treturn sectorRepository;\n\t}\n\n\t/**\n\t * Initialises the world by loading definitions from the specified file system.\n\t * \n\t * @param release The release number.\n\t * @param fs The file system.\n\t * @param manager The plugin manager. TODO move this.\n\t * @throws IOException If an I/O error occurs.\n\t */\n\tpublic void init(int release, IndexedFileSystem fs, PluginManager manager) throws Exception {\n\t\tthis.releaseNumber = release;\n\n\t\tItemDefinitionDecoder itemDefDecoder = new ItemDefinitionDecoder(fs);\n\t\tItemDefinition[] itemDefs = itemDefDecoder.decode();\n\t\tItemDefinition.init(itemDefs);\n\t\tlogger.info(\"Loaded \" + itemDefs.length + \" item definitions.\");\n\n\t\ttry (InputStream is = new BufferedInputStream(new FileInputStream(\"data/equipment-\" + release + \".dat\"))) {\n\t\t\tEquipmentDefinitionParser parser = new EquipmentDefinitionParser(is);\n\t\t\tEquipmentDefinition[] defs = parser.parse();\n\t\t\tEquipmentDefinition.init(defs);\n\t\t\tlogger.info(\"Loaded \" + defs.length + \" equipment definitions.\");\n\t\t}\n\n\t\tNpcDefinitionDecoder npcDecoder = new NpcDefinitionDecoder(fs);\n\t\tNpcDefinition[] npcDefs = npcDecoder.decode();\n\t\tNpcDefinition.init(npcDefs);\n\t\tlogger.info(\"Loaded \" + npcDefs.length + \" npc definitions.\");\n\n\t\tObjectDefinitionDecoder objectDecoder = new ObjectDefinitionDecoder(fs);\n\t\tObjectDefinition[] objDefs = objectDecoder.decode();\n\t\tObjectDefinition.init(objDefs);\n\t\tlogger.info(\"Loaded \" + objDefs.length + \" object definitions.\");\n\n\t\tStaticObjectDecoder staticDecoder = new StaticObjectDecoder(fs);\n\t\tGameObject[] objects = staticDecoder.decode();\n\t\tplaceEntities(objects);\n\t\tlogger.info(\"Loaded \" + objects.length + \" static objects.\");\n\n\t\tmanager.start();\n\t\tpluginManager = manager; // TODO move!!\n\t}\n\n\t/**\n\t * Checks if the {@link Player} with the specified name is online.\n\t * \n\t * @param username The name.\n\t * @return {@code true} if the player is online, otherwise {@code false}.\n\t */\n\tpublic boolean isPlayerOnline(String username) {\n\t\treturn players.get(NameUtil.encodeBase37(username.toLowerCase())) != null;\n\t}\n\n\t/**\n\t * Adds entities to sectors in the {@link SectorRepository}.\n\t * \n\t * @param entities The entities.\n\t * @return {@code true} if all entities were added successfully, otherwise {@code false}.\n\t */\n\tprivate boolean placeEntities(Entity... entities) {\n\t\tboolean success = true;\n\n\t\tfor (Entity entity : entities) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(entity.getPosition()));\n\t\t\tsuccess &= sector.addEntity(entity);\n\t\t}\n\t\treturn success;\n\t}\n\n\t/**\n\t * Pulses the world.\n\t */\n\tpublic void pulse() {\n\t\tscheduler.pulse();\n\t}\n\n\t/**\n\t * Registers the specified npc.\n\t * \n\t * @param npc The npc.\n\t * @return {@code true} if the npc registered successfully, otherwise {@code false}.\n\t */\n\tpublic boolean register(final Npc npc) {\n\t\tboolean success = npcRepository.add(npc);\n\n\t\tif (success) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition()));\n\t\t\tsector.addEntity(npc);\n\t\t} else {\n\t\t\tlogger.warning(\"Failed to register npc, repository capacity reached: [count=\" + npcRepository.size() + \"]\");\n\t\t}\n\t\treturn success;\n\t}\n\n\t/**\n\t * Registers the specified player.\n\t * \n\t * @param player The player.\n\t * @return A {@link RegistrationStatus}.\n\t */\n\tpublic RegistrationStatus register(final Player player) {\n\t\tif (isPlayerOnline(player.getUsername())) {\n\t\t\treturn RegistrationStatus.ALREADY_ONLINE;\n\t\t}\n\n\t\tboolean success = playerRepository.add(player)\n\t\t\t\t&& players.put(NameUtil.encodeBase37(player.getUsername().toLowerCase()), player) == null;\n\t\tif (success) {\n\t\t\tlogger.info(\"Registered player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition()));\n\t\t\tsector.addEntity(player);\n\t\t\treturn RegistrationStatus.OK;\n\t\t}\n\n\t\tlogger.warning(\"Failed to register player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\t\treturn RegistrationStatus.WORLD_FULL;\n\t}\n\n\t/**\n\t * Schedules a new task.\n\t * \n\t * @param task The {@link ScheduledTask}.\n\t */\n\tpublic boolean schedule(ScheduledTask task) {\n\t\treturn scheduler.schedule(task);\n\t}\n\n\t/**\n\t * Unregisters the specified {@link Npc}.\n\t * \n\t * @param npc The npc.\n\t */\n\tpublic void unregister(final Npc npc) {\n\t\tif (npcRepository.remove(npc)) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition()));\n\t\t\tsector.removeEntity(npc);\n\t\t} else {\n\t\t\tlogger.warning(\"Could not find npc \" + npc + \" to unregister!\");\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters the specified player.\n\t * \n\t * @param player The player.\n\t */\n\tpublic void unregister(final Player player) {\n\t\tif (playerRepository.remove(player)\n\t\t\t\t& players.remove(NameUtil.encodeBase37(player.getUsername().toLowerCase())) == player) {\n\t\t\tlogger.info(\"Unregistered player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition()));\n\t\t\tsector.removeEntity(player);\n\t\t\tlogoutDispatcher.dispatch(player);\n\t\t} else {\n\t\t\tlogger.warning(\"Could not find player \" + player + \" to unregister!\");\n\t\t}\n\t}\n\n}\n"},"new_file":{"kind":"string","value":"src/org/apollo/game/model/World.java"},"old_contents":{"kind":"string","value":"package org.apollo.game.model;\n\nimport java.io.BufferedInputStream;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.logging.Logger;\n\nimport org.apollo.Service;\nimport org.apollo.fs.IndexedFileSystem;\nimport org.apollo.fs.decoder.ItemDefinitionDecoder;\nimport org.apollo.fs.decoder.NpcDefinitionDecoder;\nimport org.apollo.fs.decoder.ObjectDefinitionDecoder;\nimport org.apollo.fs.decoder.StaticObjectDecoder;\nimport org.apollo.game.command.CommandDispatcher;\nimport org.apollo.game.login.LoginDispatcher;\nimport org.apollo.game.login.LogoutDispatcher;\nimport org.apollo.game.model.def.EquipmentDefinition;\nimport org.apollo.game.model.def.ItemDefinition;\nimport org.apollo.game.model.def.NpcDefinition;\nimport org.apollo.game.model.def.ObjectDefinition;\nimport org.apollo.game.model.obj.GameObject;\nimport org.apollo.game.model.sector.Sector;\nimport org.apollo.game.model.sector.SectorCoordinates;\nimport org.apollo.game.model.sector.SectorRepository;\nimport org.apollo.game.scheduling.ScheduledTask;\nimport org.apollo.game.scheduling.Scheduler;\nimport org.apollo.io.EquipmentDefinitionParser;\nimport org.apollo.util.MobRepository;\nimport org.apollo.util.NameUtil;\nimport org.apollo.util.plugin.PluginManager;\n\n/**\n * The world class is a singleton which contains objects like the {@link MobRepository} for players and NPCs. It should\n * only contain things relevant to the in-game world and not classes which deal with I/O and such (these may be better\n * off inside some custom {@link Service} or other code, however, the circumstances are rare).\n * \n * @author Graham\n */\npublic final class World {\n\n\t/**\n\t * Represents the different status codes for registering a player.\n\t * \n\t * @author Graham\n\t */\n\tpublic enum RegistrationStatus {\n\n\t\t/**\n\t\t * Indicates that the player is already online.\n\t\t */\n\t\tALREADY_ONLINE,\n\n\t\t/**\n\t\t * Indicates that the player was registered successfully.\n\t\t */\n\t\tOK,\n\n\t\t/**\n\t\t * Indicates the world is full.\n\t\t */\n\t\tWORLD_FULL;\n\n\t}\n\n\t/**\n\t * The logger for this class.\n\t */\n\tprivate static final Logger logger = Logger.getLogger(World.class.getName());\n\n\t/**\n\t * The world.\n\t */\n\tprivate static final World world = new World();\n\n\t/**\n\t * Gets the world.\n\t * \n\t * @return The world.\n\t */\n\tpublic static World getWorld() {\n\t\treturn world;\n\t}\n\n\t/**\n\t * The command dispatcher.\n\t */\n\tprivate final CommandDispatcher commandDispatcher = new CommandDispatcher();\n\n\t/**\n\t * The login dispatcher.\n\t */\n\tprivate final LoginDispatcher loginDispatcher = new LoginDispatcher();\n\n\t/**\n\t * The logout dispatcher.\n\t */\n\tprivate final LogoutDispatcher logoutDispatcher = new LogoutDispatcher();\n\n\t/**\n\t * The {@link MobRepository} of {@link Npc}s.\n\t */\n\tprivate final MobRepository npcRepository = new MobRepository<>(WorldConstants.MAXIMUM_NPCS);\n\n\t/**\n\t * The {@link MobRepository} of {@link Player}s.\n\t */\n\tprivate final MobRepository playerRepository = new MobRepository<>(WorldConstants.MAXIMUM_PLAYERS);\n\n\t/**\n\t * A {@link Map} of player usernames and the player objects.\n\t */\n\tprivate final Map players = new HashMap<>();\n\n\t/**\n\t * The {@link PluginManager}. TODO: better place than here!!\n\t */\n\tprivate PluginManager pluginManager;\n\n\t/**\n\t * The release number (i.e. version) of this world.\n\t */\n\tprivate int releaseNumber;\n\n\t/**\n\t * The scheduler.\n\t */\n\tprivate final Scheduler scheduler = new Scheduler();\n\n\t/**\n\t * This world's {@link SectorRepository}.\n\t */\n\tprivate final SectorRepository sectorRepository = new SectorRepository(false);\n\n\t/**\n\t * Creates the world.\n\t */\n\tprivate World() {\n\n\t}\n\n\t/**\n\t * Gets the command dispatcher.\n\t * \n\t * @return The command dispatcher.\n\t */\n\tpublic CommandDispatcher getCommandDispatcher() {\n\t\treturn commandDispatcher;\n\t}\n\n\t/**\n\t * Gets the {@link LoginDispatcher}.\n\t * \n\t * @return The dispatcher.\n\t */\n\tpublic LoginDispatcher getLoginDispatcher() {\n\t\treturn loginDispatcher;\n\t}\n\n\t/**\n\t * Gets the {@link LogoutDispatcher}.\n\t * \n\t * @return The dispatcher.\n\t */\n\tpublic LogoutDispatcher getLogoutDispatcher() {\n\t\treturn logoutDispatcher;\n\t}\n\n\t/**\n\t * Gets the npc repository.\n\t * \n\t * @return The npc repository.\n\t */\n\tpublic MobRepository getNpcRepository() {\n\t\treturn npcRepository;\n\t}\n\n\t/**\n\t * Gets the {@link Player} with the specified username. Note that this will return {@code null} if the player is\n\t * offline.\n\t * \n\t * @param username The username.\n\t * @return The player.\n\t */\n\tpublic Player getPlayer(String username) {\n\t\treturn players.get(NameUtil.encodeBase37(username.toLowerCase()));\n\t}\n\n\t/**\n\t * Gets the player repository.\n\t * \n\t * @return The player repository.\n\t */\n\tpublic MobRepository getPlayerRepository() {\n\t\treturn playerRepository;\n\t}\n\n\t/**\n\t * Gets the plugin manager. TODO should this be here?\n\t * \n\t * @return The plugin manager.\n\t */\n\tpublic PluginManager getPluginManager() {\n\t\treturn pluginManager;\n\t}\n\n\t/**\n\t * Gets the release number of this world.\n\t * \n\t * @return The release number.\n\t */\n\tpublic int getReleaseNumber() {\n\t\treturn releaseNumber;\n\t}\n\n\t/**\n\t * Gets this world's {@link SectorRepository}.\n\t * \n\t * @return The sector repository.\n\t */\n\tpublic SectorRepository getSectorRepository() {\n\t\treturn sectorRepository;\n\t}\n\n\t/**\n\t * Initialises the world by loading definitions from the specified file system.\n\t * \n\t * @param release The release number.\n\t * @param fs The file system.\n\t * @param manager The plugin manager. TODO move this.\n\t * @throws IOException If an I/O error occurs.\n\t */\n\tpublic void init(int release, IndexedFileSystem fs, PluginManager manager) throws Exception {\n\t\tthis.releaseNumber = release;\n\n\t\tItemDefinitionDecoder itemDefDecoder = new ItemDefinitionDecoder(fs);\n\t\tItemDefinition[] itemDefs = itemDefDecoder.decode();\n\t\tItemDefinition.init(itemDefs);\n\t\tlogger.info(\"Loaded \" + itemDefs.length + \" item definitions.\");\n\n\t\ttry (InputStream is = new BufferedInputStream(new FileInputStream(\"data/equipment-\" + release + \".dat\"))) {\n\t\t\tEquipmentDefinitionParser parser = new EquipmentDefinitionParser(is);\n\t\t\tEquipmentDefinition[] defs = parser.parse();\n\t\t\tEquipmentDefinition.init(defs);\n\t\t\tlogger.info(\"Loaded \" + defs.length + \" equipment definitions.\");\n\t\t}\n\n\t\tNpcDefinitionDecoder npcDecoder = new NpcDefinitionDecoder(fs);\n\t\tNpcDefinition[] npcDefs = npcDecoder.decode();\n\t\tNpcDefinition.init(npcDefs);\n\t\tlogger.info(\"Loaded \" + npcDefs.length + \" npc definitions.\");\n\n\t\tObjectDefinitionDecoder objectDecoder = new ObjectDefinitionDecoder(fs);\n\t\tObjectDefinition[] objDefs = objectDecoder.decode();\n\t\tObjectDefinition.init(objDefs);\n\t\tlogger.info(\"Loaded \" + objDefs.length + \" object definitions.\");\n\n\t\tStaticObjectDecoder staticDecoder = new StaticObjectDecoder(fs);\n\t\tGameObject[] objects = staticDecoder.decode();\n\t\tplaceEntities(objects);\n\t\tlogger.info(\"Loaded \" + objects.length + \" static objects.\");\n\n\t\tmanager.start();\n\t\tpluginManager = manager; // TODO move!!\n\t}\n\n\t/**\n\t * Checks if the {@link Player} with the specified name is online.\n\t * \n\t * @param username The name.\n\t * @return {@code true} if the player is online, otherwise {@code false}.\n\t */\n\tpublic boolean isPlayerOnline(String username) {\n\t\treturn players.get(NameUtil.encodeBase37(username.toLowerCase())) != null;\n\t}\n\n\t/**\n\t * Adds entities to sectors in the {@link SectorRepository}.\n\t * \n\t * @param entities The entities.\n\t * @return {@code true} if all entities were added successfully, otherwise {@code false}.\n\t */\n\tprivate boolean placeEntities(Entity... entities) {\n\t\tboolean success = true;\n\n\t\tfor (Entity entity : entities) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(entity.getPosition()));\n\t\t\tsuccess &= sector.addEntity(entity);\n\t\t}\n\t\treturn success;\n\t}\n\n\t/**\n\t * Pulses the world.\n\t */\n\tpublic void pulse() {\n\t\tscheduler.pulse();\n\t}\n\n\t/**\n\t * Registers the specified npc.\n\t * \n\t * @param npc The npc.\n\t * @return {@code true} if the npc registered successfully, otherwise {@code false}.\n\t */\n\tpublic boolean register(final Npc npc) {\n\t\tboolean success = npcRepository.add(npc);\n\n\t\tif (success) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition()));\n\t\t\tsector.addEntity(npc);\n\t\t} else {\n\t\t\tlogger.warning(\"Failed to register npc, repository capacity reached: [count=\" + npcRepository.size() + \"]\");\n\t\t}\n\t\treturn success;\n\t}\n\n\t/**\n\t * Registers the specified player.\n\t * \n\t * @param player The player.\n\t * @return A {@link RegistrationStatus}.\n\t */\n\tpublic RegistrationStatus register(final Player player) {\n\t\tif (isPlayerOnline(player.getUsername())) {\n\t\t\treturn RegistrationStatus.ALREADY_ONLINE;\n\t\t}\n\n\t\tboolean success = playerRepository.add(player)\n\t\t\t\t& players.put(NameUtil.encodeBase37(player.getUsername().toLowerCase()), player) == null;\n\t\tif (success) {\n\t\t\tlogger.info(\"Registered player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition()));\n\t\t\tsector.addEntity(player);\n\t\t\treturn RegistrationStatus.OK;\n\t\t}\n\n\t\tlogger.warning(\"Failed to register player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\t\treturn RegistrationStatus.WORLD_FULL;\n\t}\n\n\t/**\n\t * Schedules a new task.\n\t * \n\t * @param task The {@link ScheduledTask}.\n\t */\n\tpublic boolean schedule(ScheduledTask task) {\n\t\treturn scheduler.schedule(task);\n\t}\n\n\t/**\n\t * Unregisters the specified {@link Npc}.\n\t * \n\t * @param npc The npc.\n\t */\n\tpublic void unregister(final Npc npc) {\n\t\tif (npcRepository.remove(npc)) {\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(npc.getPosition()));\n\t\t\tsector.removeEntity(npc);\n\t\t} else {\n\t\t\tlogger.warning(\"Could not find npc \" + npc + \" to unregister!\");\n\t\t}\n\t}\n\n\t/**\n\t * Unregisters the specified player.\n\t * \n\t * @param player The player.\n\t */\n\tpublic void unregister(final Player player) {\n\t\tif (playerRepository.remove(player)\n\t\t\t\t& players.remove(NameUtil.encodeBase37(player.getUsername().toLowerCase())) == player) {\n\t\t\tlogger.info(\"Unregistered player: \" + player + \" [count=\" + playerRepository.size() + \"]\");\n\n\t\t\tSector sector = sectorRepository.get(SectorCoordinates.fromPosition(player.getPosition()));\n\t\t\tsector.removeEntity(player);\n\t\t\tlogoutDispatcher.dispatch(player);\n\t\t} else {\n\t\t\tlogger.warning(\"Could not find player \" + player + \" to unregister!\");\n\t\t}\n\t}\n\n}"},"message":{"kind":"string","value":"Update World.java.\n\nIf the first operand is false (meaning the world is full) the bitwise AND operation will still check the second operand, thus adding them to the online players list. the player will never be unregistered (removed from the player list) because they they never registered. the server will always report them as online and logged in, even though this is not the case."},"old_file":{"kind":"string","value":"src/org/apollo/game/model/World.java"},"subject":{"kind":"string","value":"Update World.java."}}},{"rowIdx":145826,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"isc"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"14e509dfd287a1142ede2d745782b130d6416471"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"badlogic/avian,badlogic/avian,bgould/avian,lostdj/avian,dicej/avian,joshuawarner32/avian,MaartenR/avian,ucdseniordesign/avian,bigfatbrowncat/avian-pack.avian,lostdj/avian,joshuawarner32/avian,badlogic/avian,bigfatbrowncat/avian-pack.avian,marcinolawski/avian,lostdj/avian,joshuawarner32/avian,dicej/avian,joshuawarner32/avian,MaartenR/avian,ucdseniordesign/avian,lostdj/avian,marcinolawski/avian,dicej/avian,minor-jason/avian,lwahlmeier/avian,badlogic/avian,bgould/avian,minor-jason/avian,lwahlmeier/avian,bgould/avian,getlantern/avian,bigfatbrowncat/avian-pack.avian,bgould/avian,ucdseniordesign/avian,marcinolawski/avian,MaartenR/avian,lwahlmeier/avian,getlantern/avian,minor-jason/avian,getlantern/avian,dicej/avian,getlantern/avian,marcinolawski/avian,lwahlmeier/avian,MaartenR/avian,ucdseniordesign/avian,minor-jason/avian,bigfatbrowncat/avian-pack.avian"},"new_contents":{"kind":"string","value":"public class Subroutine {\n private static void expect(boolean v) {\n if (! v) throw new RuntimeException();\n }\n\n // This test is intended to cover the jsr and ret instructions.\n // However, recent Sun javac versions avoid generating these\n // instructions by default, so we must compile this class using\n // -source 1.2 -target 1.1 -XDjsrlimit=0.\n //\n // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4381996\n //\n private static void test(boolean throw_, boolean predicate) {\n int x = 42;\n int y = 99;\n int a = 0;\n try {\n try {\n int z = x + y;\n if (throw_) throw new DummyException();\n if (predicate) {\n return;\n }\n Integer.valueOf(z).toString();\n } finally {\n a = x + y;\n System.gc();\n }\n expect(a == x + y);\n } catch (DummyException e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n test(false, false);\n test(false, true);\n test(true, false);\n }\n\n private static class DummyException extends RuntimeException { }\n}\n"},"new_file":{"kind":"string","value":"test/Subroutine.java"},"old_contents":{"kind":"string","value":"public class Subroutine {\n private static void expect(boolean v) {\n if (! v) throw new RuntimeException();\n }\n\n // This test is intended to cover the jsr and ret instructions.\n // However, recent Sun javac versions avoid generating these\n // instructions by default, so we must compile this class using\n // -source 1.2 -target 1.1 -XDjsrlimit=0.\n //\n // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4381996\n //\n private static void test(boolean throw_) {\n int x = 42;\n int y = 99;\n int a = 0;\n try {\n try {\n int z = x + y;\n if (throw_) throw new DummyException();\n Integer.valueOf(z).toString();\n } finally {\n a = x + y;\n System.gc();\n }\n expect(a == x + y);\n } catch (DummyException e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n test(false);\n test(true);\n }\n\n private static class DummyException extends RuntimeException { }\n}\n"},"message":{"kind":"string","value":"add additional jsr test to Subroutine\n"},"old_file":{"kind":"string","value":"test/Subroutine.java"},"subject":{"kind":"string","value":"add additional jsr test to Subroutine"}}},{"rowIdx":145827,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"437515fa2a203b0e826d02827ed18efc317ed703"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK,Microsoft/ProjectOxford-ClientSDK"},"new_contents":{"kind":"string","value":"//\n// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license.\n//\n// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services\n//\n// Microsoft Cognitive Services (formerly Project Oxford) GitHub:\n// https://github.com/Microsoft/ProjectOxford-ClientSDK\n//\n// Copyright (c) Microsoft Corporation\n// All rights reserved.\n//\n// MIT License:\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"\"AS IS\"\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\npackage com.microsoft.projectoxford.emotion.contract;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\npublic class Scores {\n public double anger;\n public double contempt;\n public double disgust;\n public double fear;\n public double happiness;\n public double neutral;\n public double sadness;\n public double surprise;\n \n public List> ToRankedList(Order order)\n {\n\t\t\n // create a Map to store each entry\n\t Map collection = new HashMap() ;\n\t\t\n\t // add each entry with its own key and value\n\t collection.put(\"ANGER\",anger);\n\t collection.put(\"CONTEMPT\",contempt);\n\t collection.put(\"DISGUST\",disgust);\n\t collection.put(\"FEAR\",fear);\n\t collection.put(\"HAPPINESS\",happiness);\n\t collection.put(\"NEUTRAL\",neutral);\n\t collection.put(\"SADNESS\",sadness);\n\t collection.put(\"SURPRISE\",surprise);\n\n\t // create a list with the entries\n\t List> list = new ArrayList>(collection.entrySet());\n\t\t\n\t // we are going to create a comparator according to the value of the enum order\n\t switch (order) \n\t {\n\t case ASCENDING:\n\t Collections.sort(list, new Comparator>() {\n\t\t @Override\n\t\t\tpublic int compare(Entry first, Entry second) {\n\t\t // we should compare the value of the first entry and the value of the second entry\n\t\t\t return first.getValue().compareTo(second.getValue());\n\t\t\t}\n\t\t });\n\t\t break;\n\t\t\t\n\t\tcase DESCENDING:\n\t\t // for ordering descending we should create a reverse order comparator \n\t\t Collections.sort(list, Collections.reverseOrder(new Comparator>() {\n\t\t @Override\n\t\t\t public int compare(Entry first, Entry second) {\n\t\t\t return first.getValue().compareTo(second.getValue());\n\t\t\t }\n\t\t })); \n\t\t break;\n\t\t\t\t\n\t\tdefault:\n\t\t break;\n\t}\n\n return list;\n \n }\n}\n"},"new_file":{"kind":"string","value":"Emotion/Android/ClientLibrary/lib/src/main/java/com/microsoft/projectoxford/emotion/contract/Scores.java"},"old_contents":{"kind":"string","value":"//\n// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license.\n//\n// Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services\n//\n// Microsoft Cognitive Services (formerly Project Oxford) GitHub:\n// https://github.com/Microsoft/ProjectOxford-ClientSDK\n//\n// Copyright (c) Microsoft Corporation\n// All rights reserved.\n//\n// MIT License:\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"\"AS IS\"\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\npackage com.microsoft.projectoxford.emotion.contract;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\npublic class Scores {\n public double anger;\n public double contempt;\n public double disgust;\n public double fear;\n public double happiness;\n public double neutral;\n public double sadness;\n public double surprise;\n \n public List> ToRankedList(Order order)\n {\n\t\t\n\t// create a Map to store each entry\n\tMap collection = new HashMap() ;\n\t\t\n\t// add each entry with its own key and value\n\tcollection.put(\"ANGER\",anger);\n\tcollection.put(\"CONTEMPT\",contempt);\n\tcollection.put(\"DISGUST\",disgust);\n\tcollection.put(\"FEAR\",fear);\n\tcollection.put(\"HAPPINESS\",happiness);\n\tcollection.put(\"NEUTRAL\",neutral);\n\tcollection.put(\"SADNESS\",sadness);\n\tcollection.put(\"SURPRISE\",surprise);\n\n\t// create a list with the entries\n\tList> list = new ArrayList>(collection.entrySet());\n\t\t\n\t// we are going to create a comparator according to the value of the enum order\n\tswitch (order) \n\t{\n\t\tcase ASCENDING:\n\t\t\tCollections.sort(list, new Comparator>() {\n\t\t\t\t@Override\n\t\t\t public int compare(Entry first, Entry second) {\n\t\t\t \t// we should compare the value of the first entry and the value of the second entry\n\t\t\t return first.getValue().compareTo(second.getValue());\n\t\t\t }\n\t\t\t});\n\t\t\tbreak;\n\t\t\t\n\t\tcase DESCENDING:\n\t\t\t// for ordering descending we should create a reverse order comparator \n\t\t\tCollections.sort(list, Collections.reverseOrder(new Comparator>() {\n\t\t\t @Override\n\t\t\t public int compare(Entry first, Entry second) {\n\t\t\t return first.getValue().compareTo(second.getValue());\n\t\t\t }\n\t\t\t})); \n\t\t\tbreak;\n\t\t\t\t\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n return list;\n \n }\n}\n"},"message":{"kind":"string","value":"Identation fixed"},"old_file":{"kind":"string","value":"Emotion/Android/ClientLibrary/lib/src/main/java/com/microsoft/projectoxford/emotion/contract/Scores.java"},"subject":{"kind":"string","value":"Identation fixed"}}},{"rowIdx":145828,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b373b3b4588b022de390c40116b51145949304e5"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"EasyBatch/easybatch-framework,EasyBatch/easybatch-framework"},"new_contents":{"kind":"string","value":"package org.easybatch.extensions.stream;\n\nimport org.easybatch.core.reader.RecordReader;\nimport org.easybatch.core.record.GenericRecord;\nimport org.easybatch.core.record.Header;\nimport org.easybatch.core.record.Record;\n\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.stream.Stream;\n\n/**\n * Reader that reads records form a {@link Stream}.\n *\n * This reader produces {@link GenericRecord} instances.\n *\n * @param Type of elements in the stream.\n * @author Charles Fleury\n * @since 5.0\n */\npublic class StreamRecordReader implements RecordReader {\n\n private static final String DEFAULT_DATASOURCE_NAME = \"DATASOURCE\";\n\n protected String datasource;\n protected Stream stream;\n protected Iterator iterator;\n protected long currentRecordNumber;\n\n /**\n * Create a {@link StreamRecordReader} to read record from a {@link Stream}.\n *\n * @param stream to read record from\n */\n public StreamRecordReader(final Stream stream) {\n this(stream, DEFAULT_DATASOURCE_NAME);\n }\n\n /**\n * Create a {@link StreamRecordReader} to read record from a {@link Stream}.\n *\n * @param stream to read record from\n * @param datasource name (default to DEFAULT_DATASOURCE_NAME)\n */\n public StreamRecordReader(final Stream stream, final String datasource) {\n this.stream = stream;\n this.datasource = datasource;\n }\n\n /**\n * Open the reader.\n */\n @Override\n public void open() throws Exception {\n if (stream == null) {\n throw new IllegalArgumentException(\"stream must not be null\");\n }\n\n if (datasource == null || datasource.isEmpty()) {\n datasource = DEFAULT_DATASOURCE_NAME;\n }\n\n currentRecordNumber = 0;\n iterator = stream.iterator();\n }\n\n /**\n * Read next record from the data source.\n *\n * @return the next record from the data source.\n */\n @Override\n public Record readRecord() throws Exception {\n if (iterator.hasNext()) {\n Header header = new Header(++currentRecordNumber, datasource, new Date());\n return new GenericRecord<>(header, iterator.next());\n } else {\n return null;\n }\n }\n\n /**\n * Close the reader.\n */\n @Override\n public void close() throws Exception {\n stream.close();\n }\n}\n"},"new_file":{"kind":"string","value":"easybatch-extensions/easybatch-stream/src/main/java/org/easybatch/extensions/stream/StreamRecordReader.java"},"old_contents":{"kind":"string","value":"package org.easybatch.extensions.stream;\n\nimport org.easybatch.core.reader.RecordReader;\nimport org.easybatch.core.record.GenericRecord;\nimport org.easybatch.core.record.Header;\nimport org.easybatch.core.record.Record;\n\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.stream.Stream;\n\n/**\n * Reader that reads records form a {@link Stream}.\n *\n * This reader produces {@link GenericRecord} instances.\n *\n * @param Type of elements in the stream.\n * @author Charles Fleury\n * @since 5.0\n */\npublic class StreamRecordReader implements RecordReader {\n\n private static final String DEFAULT_DATASOURCE_NAME = \"DATASOURCE\";\n\n protected String datasource;\n protected Stream stream;\n protected Iterator iterator;\n protected long currentRecordNumber;\n\n /**\n * Create a {@link StreamRecordReader} to read record from a {@link Stream}.\n *\n * @param stream to read record from\n */\n public StreamRecordReader(final Stream stream) {\n this(stream, DEFAULT_DATASOURCE_NAME);\n }\n\n /**\n * Create a {@link StreamRecordReader} to read record from a {@link Stream}.\n *\n * @param stream to read record from\n * @param datasource name (default to DEFAULT_DATASOURCE_NAME)\n */\n public StreamRecordReader(final Stream stream, final String datasource) {\n this.stream = stream;\n this.datasource = datasource;\n }\n\n /**\n * Open the reader.\n */\n @Override\n public void open() throws Exception {\n if (stream == null) {\n throw new IllegalArgumentException(\"stream must not be null\");\n }\n\n if (datasource == null || datasource.isEmpty()) {\n datasource = DEFAULT_DATASOURCE_NAME;\n }\n\n currentRecordNumber = 0;\n iterator = stream.iterator();\n }\n\n /**\n * Read next record from the data source.\n *\n * @return the next record from the data source.\n */\n @Override\n public Record readRecord() throws Exception {\n if (iterator.hasNext()) {\n Header header = new Header(++currentRecordNumber, datasource, new Date());\n return new GenericRecord<>(header, iterator.next());\n } else {\n return null;\n }\n }\n\n /**\n * Close the reader.\n */\n @Override\n public void close() throws Exception {\n // no op\n }\n}\n"},"message":{"kind":"string","value":"close the stream in the end of job\n"},"old_file":{"kind":"string","value":"easybatch-extensions/easybatch-stream/src/main/java/org/easybatch/extensions/stream/StreamRecordReader.java"},"subject":{"kind":"string","value":"close the stream in the end of job"}}},{"rowIdx":145829,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"b8cfc2274706d2d74e32323b558c114fcea05f2b"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"kmdouglass/Micro-Manager,kmdouglass/Micro-Manager"},"new_contents":{"kind":"string","value":"///////////////////////////////////////////////////////////////////////////////\n//FILE: MMStudioMainFrame.java\n//PROJECT: Micro-Manager\n//SUBSYSTEM: mmstudio\n//-----------------------------------------------------------------------------\n//AUTHOR: Nenad Amodaj, nenad@amodaj.com, Jul 18, 2005\n// Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard\n//COPYRIGHT: University of California, San Francisco, 2006-2013\n// 100X Imaging Inc, www.100ximaging.com, 2008\n//LICENSE: This file is distributed under the BSD license.\n// License text is included with the source distribution.\n// This file is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n// IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n//CVS: $Id$\n//\npackage org.micromanager;\n\nimport ij.IJ;\nimport ij.ImageJ;\nimport ij.ImagePlus;\nimport ij.WindowManager;\nimport ij.gui.Line;\nimport ij.gui.Roi;\nimport ij.process.ImageProcessor;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.Rectangle;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.FocusAdapter;\nimport java.awt.event.FocusEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.geom.Point2D;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\nimport javax.swing.AbstractButton;\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JCheckBoxMenuItem;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JSplitPane;\nimport javax.swing.JTextField;\nimport javax.swing.JToggleButton;\nimport javax.swing.SpringLayout;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\nimport javax.swing.ToolTipManager;\nimport javax.swing.UIManager;\n\nimport mmcorej.CMMCore;\nimport mmcorej.DeviceType;\nimport mmcorej.MMCoreJ;\nimport mmcorej.MMEventCallback;\nimport mmcorej.StrVector;\n\nimport org.json.JSONObject;\nimport org.micromanager.acquisition.AcquisitionManager;\nimport org.micromanager.api.Autofocus;\nimport org.micromanager.api.DataProcessor;\nimport org.micromanager.api.MMPlugin;\nimport org.micromanager.api.MMProcessorPlugin;\nimport org.micromanager.api.MMTags;\nimport org.micromanager.api.PositionList;\nimport org.micromanager.api.ScriptInterface;\nimport org.micromanager.api.MMListenerInterface;\nimport org.micromanager.api.SequenceSettings;\nimport org.micromanager.conf2.ConfiguratorDlg2;\nimport org.micromanager.conf2.MMConfigFileException;\nimport org.micromanager.conf2.MicroscopeModel;\nimport org.micromanager.events.EventManager;\nimport org.micromanager.graph.GraphData;\nimport org.micromanager.graph.GraphFrame;\nimport org.micromanager.navigation.CenterAndDragListener;\nimport org.micromanager.navigation.XYZKeyListener;\nimport org.micromanager.navigation.ZWheelListener;\nimport org.micromanager.pipelineUI.PipelinePanel;\nimport org.micromanager.utils.AutofocusManager;\nimport org.micromanager.utils.ContrastSettings;\nimport org.micromanager.utils.GUIColors;\nimport org.micromanager.utils.GUIUtils;\nimport org.micromanager.utils.JavaUtils;\nimport org.micromanager.utils.MMException;\nimport org.micromanager.utils.MMScriptException;\nimport org.micromanager.utils.NumberUtils;\nimport org.micromanager.utils.TextUtils;\nimport org.micromanager.utils.WaitDialog;\n\nimport bsh.EvalError;\nimport bsh.Interpreter;\n\nimport com.swtdesigner.SwingResourceManager;\n\nimport ij.gui.ImageCanvas;\nimport ij.gui.ImageWindow;\nimport ij.gui.Toolbar;\n\nimport java.awt.*;\nimport java.awt.dnd.DropTarget;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport mmcorej.TaggedImage;\n\nimport org.json.JSONException;\nimport org.micromanager.acquisition.*;\nimport org.micromanager.api.ImageCache;\nimport org.micromanager.api.IAcquisitionEngine2010;\nimport org.micromanager.graph.HistogramSettings;\nimport org.micromanager.internalinterfaces.LiveModeListener;\nimport org.micromanager.utils.DragDropUtil;\nimport org.micromanager.utils.FileDialogs;\nimport org.micromanager.utils.FileDialogs.FileType;\nimport org.micromanager.utils.HotKeysDialog;\nimport org.micromanager.utils.ImageUtils;\nimport org.micromanager.utils.MDUtils;\nimport org.micromanager.utils.MMKeyDispatcher;\nimport org.micromanager.utils.ReportingUtils;\nimport org.micromanager.utils.UIMonitor;\n\n\n\n\n\n/*\n * Main panel and application class for the MMStudio.\n */\npublic class MMStudioMainFrame extends JFrame implements ScriptInterface {\n\n private static final String MICRO_MANAGER_TITLE = \"Micro-Manager\";\n private static final long serialVersionUID = 3556500289598574541L;\n private static final String MAIN_FRAME_X = \"x\";\n private static final String MAIN_FRAME_Y = \"y\";\n private static final String MAIN_FRAME_WIDTH = \"width\";\n private static final String MAIN_FRAME_HEIGHT = \"height\";\n private static final String MAIN_FRAME_DIVIDER_POS = \"divider_pos\";\n private static final String MAIN_EXPOSURE = \"exposure\";\n private static final String MAIN_SAVE_METHOD = \"saveMethod\";\n private static final String SYSTEM_CONFIG_FILE = \"sysconfig_file\";\n private static final String OPEN_ACQ_DIR = \"openDataDir\";\n private static final String SCRIPT_CORE_OBJECT = \"mmc\";\n private static final String SCRIPT_ACQENG_OBJECT = \"acq\";\n private static final String SCRIPT_GUI_OBJECT = \"gui\";\n private static final String AUTOFOCUS_DEVICE = \"autofocus_device\";\n private static final String MOUSE_MOVES_STAGE = \"mouse_moves_stage\";\n private static final String EXPOSURE_SETTINGS_NODE = \"MainExposureSettings\";\n private static final String CONTRAST_SETTINGS_NODE = \"MainContrastSettings\";\n private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;\n private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;\n\n\n // cfg file saving\n private static final String CFGFILE_ENTRY_BASE = \"CFGFileEntry\"; // + {0, 1, 2, 3, 4}\n // GUI components\n private JComboBox comboBinning_;\n private JComboBox shutterComboBox_;\n private JTextField textFieldExp_;\n private JLabel labelImageDimensions_;\n private JToggleButton liveButton_;\n private JCheckBox autoShutterCheckBox_;\n private MMOptions options_;\n private boolean runsAsPlugin_;\n private JCheckBoxMenuItem centerAndDragMenuItem_;\n private JButton snapButton_;\n private JButton autofocusNowButton_;\n private JButton autofocusConfigureButton_;\n private JToggleButton toggleShutterButton_;\n private GUIColors guiColors_;\n private GraphFrame profileWin_;\n private PropertyEditor propertyBrowser_;\n private CalibrationListDlg calibrationListDlg_;\n private AcqControlDlg acqControlWin_;\n\n private JMenu pluginMenu_;\n private Map pluginSubMenus_;\n private List MMListeners_\n = Collections.synchronizedList(new ArrayList());\n private List liveModeListeners_\n = Collections.synchronizedList(new ArrayList());\n private List MMFrames_\n = Collections.synchronizedList(new ArrayList());\n private AutofocusManager afMgr_;\n private final static String DEFAULT_CONFIG_FILE_NAME = \"MMConfig_demo.cfg\";\n private final static String DEFAULT_CONFIG_FILE_PROPERTY = \"org.micromanager.default.config.file\";\n private ArrayList MRUConfigFiles_;\n private static final int maxMRUCfgs_ = 5;\n private String sysConfigFile_;\n private String startupScriptFile_;\n private ConfigGroupPad configPad_;\n private LiveModeTimer liveModeTimer_;\n private GraphData lineProfileData_;\n // labels for standard devices\n private String cameraLabel_;\n private String zStageLabel_;\n private String shutterLabel_;\n private String xyStageLabel_;\n // applications settings\n private Preferences mainPrefs_;\n private Preferences systemPrefs_;\n private Preferences colorPrefs_;\n private Preferences exposurePrefs_;\n private Preferences contrastPrefs_;\n\n // MMcore\n private CMMCore core_;\n private AcquisitionWrapperEngine engine_;\n private PositionList posList_;\n private PositionListDlg posListDlg_;\n private String openAcqDirectory_ = \"\";\n private boolean running_;\n private boolean configChanged_ = false;\n private StrVector shutters_ = null;\n\n private JButton saveConfigButton_;\n private ScriptPanel scriptPanel_;\n private PipelinePanel pipelinePanel_;\n private org.micromanager.utils.HotKeys hotKeys_;\n private CenterAndDragListener centerAndDragListener_;\n private ZWheelListener zWheelListener_;\n private XYZKeyListener xyzKeyListener_;\n private AcquisitionManager acqMgr_;\n private static VirtualAcquisitionDisplay simpleDisplay_;\n private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};\n private boolean liveModeSuspended_;\n public Font defaultScriptFont_ = null;\n public static final String SIMPLE_ACQ = \"Snap/Live Window\";\n public static FileType MM_CONFIG_FILE\n = new FileType(\"MM_CONFIG_FILE\",\n \"Micro-Manager Config File\",\n \"./MyScope.cfg\",\n true, \"cfg\");\n\n // Our instance\n private static MMStudioMainFrame gui_;\n // Callback\n private CoreEventCallback cb_;\n // Lock invoked while shutting down\n private final Object shutdownLock_ = new Object();\n\n private JMenuBar menuBar_;\n private ConfigPadButtonPanel configPadButtonPanel_;\n private final JMenu switchConfigurationMenu_;\n private final MetadataPanel metadataPanel_;\n public static FileType MM_DATA_SET \n = new FileType(\"MM_DATA_SET\",\n \"Micro-Manager Image Location\",\n System.getProperty(\"user.home\") + \"/Untitled\",\n false, (String[]) null);\n private Thread acquisitionEngine2010LoadingThread_ = null;\n private Class> acquisitionEngine2010Class_ = null;\n private IAcquisitionEngine2010 acquisitionEngine2010_ = null;\n private final JSplitPane splitPane_;\n private volatile boolean ignorePropertyChanges_; \n private PluginLoader pluginLoader_;\n\n private AbstractButton setRoiButton_;\n private AbstractButton clearRoiButton_;\n\n /**\n * Simple class used to cache static info\n */\n private class StaticInfo {\n\n public long width_;\n public long height_;\n public long bytesPerPixel_;\n public long imageBitDepth_;\n public double pixSizeUm_;\n public double zPos_;\n public double x_;\n public double y_;\n }\n private StaticInfo staticInfo_ = new StaticInfo();\n \n \n /**\n * Main procedure for stand alone operation.\n */\n public static void main(String args[]) {\n try {\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n MMStudioMainFrame frame = new MMStudioMainFrame(false);\n frame.setVisible(true);\n frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n } catch (Throwable e) {\n ReportingUtils.showError(e, \"A java error has caused Micro-Manager to exit.\");\n System.exit(1);\n }\n }\n\n /**\n * MMStudioMainframe constructor\n * @param pluginStatus \n */\n @SuppressWarnings(\"LeakingThisInConstructor\")\n public MMStudioMainFrame(boolean pluginStatus) {\n org.micromanager.diagnostics.ThreadExceptionLogger.setUp();\n\n // Set up event handling early, so following code can subscribe/publish\n // events as needed.\n EventManager manager = new EventManager();\n\n startLoadingPipelineClass();\n\n options_ = new MMOptions();\n try {\n options_.loadSettings();\n } catch (NullPointerException ex) {\n ReportingUtils.logError(ex);\n }\n\n UIMonitor.enable(options_.debugLogEnabled_);\n \n guiColors_ = new GUIColors();\n\n pluginLoader_ = new PluginLoader();\n // plugins_ = new ArrayList();\n\n gui_ = this;\n\n runsAsPlugin_ = pluginStatus;\n setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,\n \"icons/microscope.gif\"));\n running_ = true;\n\n acqMgr_ = new AcquisitionManager();\n \n sysConfigFile_ = new File(DEFAULT_CONFIG_FILE_NAME).getAbsolutePath();\n sysConfigFile_ = System.getProperty(DEFAULT_CONFIG_FILE_PROPERTY,\n sysConfigFile_);\n\n if (options_.startupScript_.length() > 0) {\n startupScriptFile_ = new File(options_.startupScript_).getAbsolutePath();\n } else {\n startupScriptFile_ = \"\";\n }\n\n ReportingUtils.SetContainingFrame(gui_);\n \n \n // set the location for app preferences\n try {\n mainPrefs_ = Preferences.userNodeForPackage(this.getClass());\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n systemPrefs_ = mainPrefs_;\n \n colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" + \n AcqControlDlg.COLOR_SETTINGS_NODE);\n exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" + \n EXPOSURE_SETTINGS_NODE);\n contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" +\n CONTRAST_SETTINGS_NODE);\n \n // check system preferences\n try {\n Preferences p = Preferences.systemNodeForPackage(this.getClass());\n if (null != p) {\n // if we can not write to the systemPrefs, use AppPrefs instead\n if (JavaUtils.backingStoreAvailable(p)) {\n systemPrefs_ = p;\n }\n }\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n \n showRegistrationDialogMaybe();\n\n // load application preferences\n // NOTE: only window size and position preferences are loaded,\n // not the settings for the camera and live imaging -\n // attempting to set those automatically on startup may cause problems\n // with the hardware\n int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);\n int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);\n int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644);\n int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570);\n openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, \"\");\n try {\n ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD,\n ImageUtils.getImageStorageClass().getName()) ) );\n } catch (ClassNotFoundException ex) {\n ReportingUtils.logError(ex, \"Class not found error. Should never happen\");\n }\n\n ToolTipManager ttManager = ToolTipManager.sharedInstance();\n ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);\n ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);\n \n setBounds(x, y, width, height);\n setExitStrategy(options_.closeOnExit_);\n setTitle(MICRO_MANAGER_TITLE + \" \" + MMVersion.VERSION_STRING);\n setBackground(guiColors_.background.get((options_.displayBackground_)));\n setMinimumSize(new Dimension(605,480));\n \n menuBar_ = new JMenuBar();\n switchConfigurationMenu_ = new JMenu();\n\n setJMenuBar(menuBar_);\n\n initializeFileMenu();\n initializeToolsMenu();\n\n splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200));\n getContentPane().add(splitPane_);\n\n createTopPanelWidgets((JPanel) splitPane_.getComponent(0));\n \n metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1));\n \n setupWindowHandlers();\n \n // Add our own keyboard manager that handles Micro-Manager shortcuts\n MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);\n KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);\n DropTarget dropTarget = new DropTarget(this, new DragDropUtil());\n\n }\n \n private void setupWindowHandlers() {\n // add window listeners\n addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n closeSequence(false);\n }\n\n @Override\n public void windowOpened(WindowEvent e) {\n // -------------------\n // initialize hardware\n // -------------------\n try {\n core_ = new CMMCore();\n } catch(UnsatisfiedLinkError ex) {\n ReportingUtils.showError(ex, \"Failed to load the MMCoreJ_wrap native library\");\n return;\n }\n\n ReportingUtils.setCore(core_);\n core_.enableDebugLog(options_.debugLogEnabled_);\n logStartupProperties();\n \n cameraLabel_ = \"\";\n shutterLabel_ = \"\";\n zStageLabel_ = \"\";\n xyStageLabel_ = \"\";\n engine_ = new AcquisitionWrapperEngine(acqMgr_);\n // processorStackManager_ = new ProcessorStackManager(engine_);\n\n // register callback for MMCore notifications, this is a global\n // to avoid garbage collection\n cb_ = new CoreEventCallback();\n core_.registerCallback(cb_);\n\n try {\n core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);\n } catch (Exception e2) {\n ReportingUtils.showError(e2);\n }\n\n MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();\n if (parent != null) {\n engine_.setParentGUI(parent);\n }\n\n loadMRUConfigFiles();\n afMgr_ = new AutofocusManager(gui_);\n Thread pluginInitializer = initializePlugins();\n\n toFront();\n \n if (!options_.doNotAskForConfigFile_) {\n MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_);\n introDlg.setConfigFile(sysConfigFile_);\n introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));\n introDlg.setVisible(true);\n if (!introDlg.okChosen()) {\n closeSequence(false);\n return;\n }\n sysConfigFile_ = introDlg.getConfigFile();\n }\n saveMRUConfigFiles();\n\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n\n paint(MMStudioMainFrame.this.getGraphics());\n\n engine_.setCore(core_, afMgr_);\n posList_ = new PositionList();\n engine_.setPositionList(posList_);\n // load (but do no show) the scriptPanel\n createScriptPanel();\n // Ditto with the image pipeline panel.\n createPipelinePanel();\n\n // Create an instance of HotKeys so that they can be read in from prefs\n hotKeys_ = new org.micromanager.utils.HotKeys();\n hotKeys_.loadSettings();\n \n // before loading the system configuration, we need to wait \n // until the plugins are loaded\n try { \n pluginInitializer.join(2000);\n } catch (InterruptedException ex) {\n ReportingUtils.logError(ex, \"Plugin loader thread was interupted\");\n }\n \n // if an error occurred during config loading, \n // do not display more errors than needed\n if (!loadSystemConfiguration())\n ReportingUtils.showErrorOn(false);\n\n executeStartupScript();\n\n\n // Create Multi-D window here but do not show it.\n // This window needs to be created in order to properly set the \"ChannelGroup\"\n // based on the Multi-D parameters\n acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_);\n addMMBackgroundListener(acqControlWin_);\n\n configPad_.setCore(core_);\n if (parent != null) {\n configPad_.setParentGUI(parent);\n }\n\n configPadButtonPanel_.setCore(core_);\n\n // initialize controls\n initializeHelpMenu();\n \n String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, \"\");\n if (afMgr_.hasDevice(afDevice)) {\n try {\n afMgr_.selectDevice(afDevice);\n } catch (MMException e1) {\n // this error should never happen\n ReportingUtils.showError(e1);\n }\n }\n\n centerAndDragListener_ = new CenterAndDragListener(gui_);\n zWheelListener_ = new ZWheelListener(core_, gui_);\n gui_.addLiveModeListener(zWheelListener_);\n xyzKeyListener_ = new XYZKeyListener(core_, gui_);\n gui_.addLiveModeListener(xyzKeyListener_);\n\n // switch error reporting back on\n ReportingUtils.showErrorOn(true);\n }\n\n private Thread initializePlugins() {\n pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, \"Plugins\");\n Thread myThread = new ThreadPluginLoading(\"Plugin loading\");\n myThread.start();\n return myThread;\n }\n\n class ThreadPluginLoading extends Thread {\n\n public ThreadPluginLoading(String string) {\n super(string);\n }\n\n @Override\n public void run() {\n // Needed for loading clojure-based jars:\n Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n pluginLoader_.loadPlugins();\n }\n }\n \n });\n \n }\n \n \n \n \n /**\n * Callback to update GUI when a change happens in the MMCore.\n */\n public class CoreEventCallback extends MMEventCallback {\n\n public CoreEventCallback() {\n super();\n }\n\n @Override\n public void onPropertiesChanged() {\n // TODO: remove test once acquisition engine is fully multithreaded\n if (engine_ != null && engine_.isAcquisitionRunning()) {\n core_.logMessage(\"Notification from MMCore ignored because acquistion is running!\", true);\n } else {\n if (ignorePropertyChanges_) {\n core_.logMessage(\"Notification from MMCore ignored since the system is still loading\", true);\n } else {\n core_.updateSystemStateCache();\n updateGUI(true);\n // update all registered listeners \n for (MMListenerInterface mmIntf : MMListeners_) {\n mmIntf.propertiesChangedAlert();\n }\n core_.logMessage(\"Notification from MMCore!\", true);\n }\n }\n }\n\n @Override\n public void onPropertyChanged(String deviceName, String propName, String propValue) {\n core_.logMessage(\"Notification for Device: \" + deviceName + \" Property: \" +\n propName + \" changed to value: \" + propValue, true);\n // update all registered listeners\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.propertyChangedAlert(deviceName, propName, propValue);\n }\n }\n\n @Override\n public void onConfigGroupChanged(String groupName, String newConfig) {\n try {\n configPad_.refreshGroup(groupName, newConfig);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.configGroupChangedAlert(groupName, newConfig);\n }\n } catch (Exception e) {\n }\n }\n \n @Override\n public void onSystemConfigurationLoaded() {\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.systemConfigurationLoaded();\n }\n }\n\n @Override\n public void onPixelSizeChanged(double newPixelSizeUm) {\n updatePixSizeUm (newPixelSizeUm);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.pixelSizeChangedAlert(newPixelSizeUm);\n }\n }\n\n @Override\n public void onStagePositionChanged(String deviceName, double pos) {\n if (deviceName.equals(zStageLabel_)) {\n updateZPos(pos);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.stagePositionChangedAlert(deviceName, pos);\n }\n }\n }\n\n @Override\n public void onStagePositionChangedRelative(String deviceName, double pos) {\n if (deviceName.equals(zStageLabel_))\n updateZPosRelative(pos);\n }\n\n @Override\n public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {\n if (deviceName.equals(xyStageLabel_)) {\n updateXYPos(xPos, yPos);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);\n }\n }\n }\n\n @Override\n public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {\n if (deviceName.equals(xyStageLabel_))\n updateXYPosRelative(xPos, yPos);\n }\n \n @Override\n public void onExposureChanged(String deviceName, double exposure) {\n if (deviceName.equals(cameraLabel_)){\n // update exposure in gui\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); \n }\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.exposureChanged(deviceName, exposure);\n }\n }\n \n }\n\n private void handleException(Exception e, String msg) {\n String errText = \"Exception occurred: \";\n if (msg.length() > 0) {\n errText += msg + \" -- \";\n }\n if (options_.debugLogEnabled_) {\n errText += e.getMessage();\n } else {\n errText += e.toString() + \"\\n\";\n ReportingUtils.showError(e);\n }\n handleError(errText);\n }\n\n private void handleException(Exception e) {\n handleException(e, \"\");\n }\n\n private void handleError(String message) {\n if (isLiveModeOn()) {\n // Should we always stop live mode on any error?\n enableLiveMode(false);\n }\n JOptionPane.showMessageDialog(this, message);\n core_.logMessage(message);\n }\n\n public ImageWindow getImageWin() {\n return getSnapLiveWin();\n }\n\n public static VirtualAcquisitionDisplay getSimpleDisplay() {\n return simpleDisplay_;\n }\n\n public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {\n simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name); \n }\n\n \n public void checkSimpleAcquisition() {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n int width = (int) core_.getImageWidth();\n int height = (int) core_.getImageHeight();\n int depth = (int) core_.getBytesPerPixel();\n int bitDepth = (int) core_.getImageBitDepth();\n int numCamChannels = (int) core_.getNumberOfCameraChannels();\n\n try {\n if (acquisitionExists(SIMPLE_ACQ)) {\n if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)\n || (getAcquisitionImageHeight(SIMPLE_ACQ) != height)\n || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)\n || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)\n || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window\n closeAcquisitionWindow(SIMPLE_ACQ);\n }\n }\n if (!acquisitionExists(SIMPLE_ACQ)) {\n openAcquisition(SIMPLE_ACQ, \"\", 1, numCamChannels, 1, true);\n if (numCamChannels > 1) {\n for (long i = 0; i < numCamChannels; i++) {\n String chName = core_.getCameraChannelName(i);\n int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();\n setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));\n setChannelName(SIMPLE_ACQ, (int) i, chName);\n }\n }\n initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);\n getAcquisition(SIMPLE_ACQ).promptToSave(false);\n getAcquisition(SIMPLE_ACQ).getAcquisitionWindow().getHyperImage().getWindow().toFront();\n this.updateCenterAndDragListener();\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n\n }\n\n\n public void checkSimpleAcquisition(TaggedImage image) {\n try {\n JSONObject tags = image.tags;\n int width = MDUtils.getWidth(tags);\n int height = MDUtils.getHeight(tags);\n int depth = MDUtils.getDepth(tags);\n int bitDepth = MDUtils.getBitDepth(tags);\n int numCamChannels = (int) core_.getNumberOfCameraChannels();\n\n if (acquisitionExists(SIMPLE_ACQ)) {\n if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)\n || (getAcquisitionImageHeight(SIMPLE_ACQ) != height)\n || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)\n || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)\n || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window\n closeAcquisitionWindow(SIMPLE_ACQ);\n // Seems that closeAcquisitionWindow also closes the acquisition...\n //closeAcquisition(SIMPLE_ACQ);\n }\n }\n if (!acquisitionExists(SIMPLE_ACQ)) {\n openAcquisition(SIMPLE_ACQ, \"\", 1, numCamChannels, 1, true);\n if (numCamChannels > 1) {\n for (long i = 0; i < numCamChannels; i++) {\n String chName = core_.getCameraChannelName(i);\n int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();\n setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));\n setChannelName(SIMPLE_ACQ, (int) i, chName);\n }\n }\n initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);\n getAcquisition(SIMPLE_ACQ).promptToSave(false);\n getAcquisition(SIMPLE_ACQ).getAcquisitionWindow().getHyperImage().getWindow().toFront();\n this.updateCenterAndDragListener();\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n\n }\n\n public void saveChannelColor(String chName, int rgb)\n {\n if (colorPrefs_ != null) {\n colorPrefs_.putInt(\"Color_\" + chName, rgb); \n } \n }\n \n public Color getChannelColor(String chName, int defaultColor)\n { \n if (colorPrefs_ != null) {\n defaultColor = colorPrefs_.getInt(\"Color_\" + chName, defaultColor);\n }\n return new Color(defaultColor);\n }\n\n\n public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException {\n ImageCache ic = display.getImageCache();\n int channels = ic.getSummaryMetadata().getInt(\"Channels\");\n if (channels == 1) {\n //RGB or monchrome\n addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments());\n } else {\n //multicamera\n for (int i = 0; i < channels; i++) {\n addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments());\n }\n }\n }\n\n private void createActiveShutterChooser(JPanel topPanel) {\n createLabel(\"Shutter\", false, topPanel, 111, 73, 158, 86); \n\n shutterComboBox_ = new JComboBox();\n shutterComboBox_.setName(\"Shutter\");\n shutterComboBox_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent arg0) {\n try {\n if (shutterComboBox_.getSelectedItem() != null) {\n core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());\n }\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n });\n GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92);\n }\n\n private void createBinningChooser(JPanel topPanel) {\n createLabel(\"Binning\", false, topPanel, 111, 43, 199, 64);\n\n comboBinning_ = new JComboBox();\n comboBinning_.setName(\"Binning\");\n comboBinning_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n comboBinning_.setMaximumRowCount(4);\n comboBinning_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n changeBinning();\n }\n });\n GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66);\n }\n\n private void createExposureField(JPanel topPanel) {\n createLabel(\"Exposure [ms]\", false, topPanel, 111, 23, 198, 39);\n\n textFieldExp_ = new JTextField();\n textFieldExp_.addFocusListener(new FocusAdapter() {\n @Override\n public void focusLost(FocusEvent fe) {\n synchronized(shutdownLock_) {\n if (core_ != null)\n setExposure();\n }\n }\n });\n textFieldExp_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n textFieldExp_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n setExposure();\n }\n });\n GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40);\n }\n\n private void toggleAutoShutter() {\n shutterLabel_ = core_.getShutterDevice();\n if (shutterLabel_.length() == 0) {\n toggleShutterButton_.setEnabled(false);\n } else {\n if (autoShutterCheckBox_.isSelected()) {\n try {\n core_.setAutoShutter(true);\n core_.setShutterOpen(false);\n toggleShutterButton_.setSelected(false);\n toggleShutterButton_.setText(\"Open\");\n toggleShutterButton_.setEnabled(false);\n } catch (Exception e2) {\n ReportingUtils.logError(e2);\n }\n } else {\n try {\n core_.setAutoShutter(false);\n core_.setShutterOpen(false);\n toggleShutterButton_.setEnabled(true);\n toggleShutterButton_.setText(\"Open\");\n } catch (Exception exc) {\n ReportingUtils.logError(exc);\n }\n }\n }\n }\n \n private void createShutterControls(JPanel topPanel) {\n autoShutterCheckBox_ = new JCheckBox();\n autoShutterCheckBox_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n autoShutterCheckBox_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n toggleAutoShutter();\n }\n });\n autoShutterCheckBox_.setIconTextGap(6);\n autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);\n autoShutterCheckBox_.setText(\"Auto shutter\");\n GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119);\n\n toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true,\n \"toggleShutterButton\", \"Open\",\n \"Open/close the shutter\",\n new Runnable() {\n public void run() {\n toggleShutter();\n }\n }, null, topPanel, 203, 96, 275, 117); // Shutter button\n }\n\n private void createCameraSettingsWidgets(JPanel topPanel) {\n createLabel(\"Camera settings\", true, topPanel, 109, 2, 211, 22);\n createExposureField(topPanel);\n createBinningChooser(topPanel);\n createActiveShutterChooser(topPanel);\n createShutterControls(topPanel);\n }\n\n private void createConfigurationControls(JPanel topPanel) {\n createLabel(\"Configuration settings\", true, topPanel, 280, 2, 430, 22);\n\n saveConfigButton_ = (JButton) GUIUtils.createButton(false,\n \"saveConfigureButton\", \"Save\",\n \"Save current presets to the configuration file\",\n new Runnable() {\n public void run() {\n saveConfigPresets();\n }\n }, null, topPanel, -80, 2, -5, 20);\n \n configPad_ = new ConfigGroupPad();\n configPadButtonPanel_ = new ConfigPadButtonPanel();\n configPadButtonPanel_.setConfigPad(configPad_);\n configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance());\n \n configPad_.setFont(new Font(\"\", Font.PLAIN, 10));\n \n GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44);\n GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20);\n }\n\n private void createMainButtons(JPanel topPanel) {\n snapButton_ = (JButton) GUIUtils.createButton(false, \"Snap\", \"Snap\",\n \"Snap single image\",\n new Runnable() {\n public void run() {\n doSnap();\n }\n }, \"camera.png\", topPanel, 7, 4, 95, 25);\n\n liveButton_ = (JToggleButton) GUIUtils.createButton(true,\n \"Live\", \"Live\",\n \"Continuous live view\",\n new Runnable() {\n public void run() {\n enableLiveMode(!isLiveModeOn());\n }\n }, \"camera_go.png\", topPanel, 7, 26, 95, 47);\n\n /* toAlbumButton_ = (JButton) */ GUIUtils.createButton(false, \"Album\", \"Album\",\n \"Acquire single frame and add to an album\",\n new Runnable() {\n public void run() {\n snapAndAddToImage5D();\n }\n }, \"camera_plus_arrow.png\", topPanel, 7, 48, 95, 69);\n\n /* MDA Button = */ GUIUtils.createButton(false,\n \"Multi-D Acq.\", \"Multi-D Acq.\",\n \"Open multi-dimensional acquisition window\",\n new Runnable() {\n public void run() {\n openAcqControlDialog();\n }\n }, \"film.png\", topPanel, 7, 70, 95, 91);\n\n /* Refresh = */ GUIUtils.createButton(false, \"Refresh\", \"Refresh\",\n \"Refresh all GUI controls directly from the hardware\",\n new Runnable() {\n public void run() {\n core_.updateSystemStateCache();\n updateGUI(true);\n }\n }, \"arrow_refresh.png\", topPanel, 7, 92, 95, 113);\n }\n\n private static MetadataPanel createMetadataPanel(JPanel bottomPanel) {\n MetadataPanel metadataPanel = new MetadataPanel();\n GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0);\n metadataPanel.setBorder(BorderFactory.createEmptyBorder());\n return metadataPanel;\n }\n\n private void createPleaLabel(JPanel topPanel) {\n JLabel citePleaLabel = new JLabel(\"Please cite Micro-Manager so funding will continue!\");\n citePleaLabel.setFont(new Font(\"Arial\", Font.PLAIN, 11));\n GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139);\n\n class Pleader extends Thread{\n Pleader(){\n super(\"pleader\");\n }\n @Override\n public void run(){\n try {\n ij.plugin.BrowserLauncher.openURL(\"https://micro-manager.org/wiki/Citing_Micro-Manager\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n\n }\n citePleaLabel.addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent e) {\n Pleader p = new Pleader();\n p.start();\n }\n });\n\n // add a listener to the main ImageJ window to catch it quitting out on us\n /*\n * The current version of ImageJ calls the command \"Quit\", which we \n * handle in MMStudioPlugin. Calling the closeSequence from here as well\n * leads to crashes since the core will be cleaned up by one of the two\n * threads doing the same thing. I do not know since which version of \n * ImageJ introduced this behavior - NS, 2014-04-26\n \n if (ij.IJ.getInstance() != null) {\n ij.IJ.getInstance().addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n //closeSequence(true);\n };\n });\n }\n */\n }\n\n private JSplitPane createSplitPane(int dividerPos) {\n JPanel topPanel = new JPanel();\n JPanel bottomPanel = new JPanel();\n topPanel.setLayout(new SpringLayout());\n topPanel.setMinimumSize(new Dimension(580, 195));\n bottomPanel.setLayout(new SpringLayout());\n JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,\n topPanel, bottomPanel);\n splitPane.setBorder(BorderFactory.createEmptyBorder());\n splitPane.setDividerLocation(dividerPos);\n splitPane.setResizeWeight(0.0);\n return splitPane;\n }\n\n private void createTopPanelWidgets(JPanel topPanel) {\n createMainButtons(topPanel);\n createCameraSettingsWidgets(topPanel);\n createPleaLabel(topPanel);\n createUtilityButtons(topPanel);\n createConfigurationControls(topPanel);\n labelImageDimensions_ = createLabel(\"\", false, topPanel, 5, -20, 0, 0);\n }\n\n private void createUtilityButtons(JPanel topPanel) {\n // ROI\n \n createLabel(\"ROI\", true, topPanel, 8, 140, 71, 154);\n \n setRoiButton_ = GUIUtils.createButton(false, \"setRoiButton\", null,\n \"Set Region Of Interest to selected rectangle\",\n new Runnable() {\n public void run() {\n setROI();\n }\n }, \"shape_handles.png\", topPanel, 7, 154, 37, 174);\n\n clearRoiButton_ = GUIUtils.createButton(false, \"clearRoiButton\", null,\n \"Reset Region of Interest to full frame\",\n new Runnable() {\n public void run() {\n clearROI();\n }\n }, \"arrow_out.png\", topPanel, 40, 154, 70, 174);\n \n // Zoom\n \n createLabel(\"Zoom\", true, topPanel, 81, 140, 139, 154);\n\n GUIUtils.createButton(false, \"zoomInButton\", null,\n \"Zoom in\",\n new Runnable() {\n public void run() {\n zoomIn();\n }\n }, \"zoom_in.png\", topPanel, 80, 154, 110, 174);\n\n GUIUtils.createButton(false, \"zoomOutButton\", null,\n \"Zoom out\",\n new Runnable() {\n public void run() {\n zoomOut();\n }\n }, \"zoom_out.png\", topPanel, 113, 154, 143, 174);\n\n // Profile\n \n createLabel(\"Profile\", true, topPanel, 154, 140, 217, 154);\n\n GUIUtils.createButton(false, \"lineProfileButton\", null,\n \"Open line profile window (requires line selection)\",\n new Runnable() {\n public void run() {\n openLineProfileWindow();\n }\n }, \"chart_curve.png\", topPanel, 153, 154, 183, 174);\n\n // Autofocus\n\n createLabel(\"Autofocus\", true, topPanel, 194, 140, 276, 154);\n\n autofocusNowButton_ = (JButton) GUIUtils.createButton(false,\n \"autofocusNowButton\", null,\n \"Autofocus now\",\n new Runnable() {\n public void run() {\n autofocusNow();\n }\n }, \"find.png\", topPanel, 193, 154, 223, 174);\n\n\n autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false,\n \"autofocusConfigureButton\", null,\n \"Set autofocus options\",\n new Runnable() {\n public void run() {\n showAutofocusDialog();\n }\n }, \"wrench_orange.png\", topPanel, 226, 154, 256, 174);\n }\n\n private void initializeFileMenu() {\n JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"File\");\n\n GUIUtils.addMenuItem(fileMenu, \"Open (Virtual)...\", null,\n new Runnable() {\n public void run() {\n new Thread() {\n @Override\n public void run() {\n openAcquisitionData(false);\n }\n }.start();\n }\n });\n\n GUIUtils.addMenuItem(fileMenu, \"Open (RAM)...\", null,\n new Runnable() {\n public void run() {\n new Thread() {\n @Override\n public void run() {\n openAcquisitionData(true);\n }\n }.start();\n }\n });\n\n fileMenu.addSeparator();\n\n GUIUtils.addMenuItem(fileMenu, \"Exit\", null,\n new Runnable() {\n public void run() {\n closeSequence(false);\n }\n });\n }\n \n private void initializeHelpMenu() {\n final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"Help\");\n \n GUIUtils.addMenuItem(helpMenu, \"User's Guide\", null,\n new Runnable() {\n public void run() {\n try {\n ij.plugin.BrowserLauncher.openURL(\"http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n });\n \n GUIUtils.addMenuItem(helpMenu, \"Configuration Guide\", null,\n new Runnable() {\n public void run() {\n try {\n ij.plugin.BrowserLauncher.openURL(\"http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n }); \n \n if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {\n GUIUtils.addMenuItem(helpMenu, \"Register your copy of Micro-Manager...\", null,\n new Runnable() {\n public void run() {\n try {\n RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);\n regDlg.setVisible(true);\n } catch (Exception e1) {\n ReportingUtils.showError(e1);\n }\n }\n });\n }\n\n GUIUtils.addMenuItem(helpMenu, \"Report Problem...\", null,\n new Runnable() {\n @Override\n public void run() {\n org.micromanager.diagnostics.gui.ProblemReportController.start(core_, options_);\n }\n });\n\n GUIUtils.addMenuItem(helpMenu, \"About Micromanager\", null,\n new Runnable() {\n public void run() {\n MMAboutDlg dlg = new MMAboutDlg();\n String versionInfo = \"MM Studio version: \" + MMVersion.VERSION_STRING;\n versionInfo += \"\\n\" + core_.getVersionInfo();\n versionInfo += \"\\n\" + core_.getAPIVersionInfo();\n versionInfo += \"\\nUser: \" + core_.getUserId();\n versionInfo += \"\\nHost: \" + core_.getHostName();\n dlg.setVersionInfo(versionInfo);\n dlg.setVisible(true);\n }\n });\n \n \n menuBar_.validate();\n }\n\n private void initializeToolsMenu() {\n // Tools menu\n \n final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"Tools\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Refresh GUI\",\n \"Refresh all GUI controls directly from the hardware\",\n new Runnable() {\n public void run() {\n core_.updateSystemStateCache();\n updateGUI(true);\n }\n },\n \"arrow_refresh.png\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Rebuild GUI\",\n \"Regenerate Micro-Manager user interface\",\n new Runnable() {\n public void run() {\n initializeGUI();\n core_.updateSystemStateCache();\n }\n });\n \n toolsMenu.addSeparator();\n \n GUIUtils.addMenuItem(toolsMenu, \"Image Pipeline...\",\n \"Display the image processing pipeline\",\n new Runnable() {\n public void run() {\n pipelinePanel_.setVisible(true);\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Script Panel...\",\n \"Open Micro-Manager script editor window\",\n new Runnable() {\n public void run() {\n scriptPanel_.setVisible(true);\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Shortcuts...\",\n \"Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts\",\n new Runnable() {\n public void run() {\n HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_)));\n //hk.setBackground(guiColors_.background.get((options_.displayBackground_)));\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Device/Property Browser...\",\n \"Open new window to view and edit property values in current configuration\",\n new Runnable() {\n public void run() {\n createPropertyEditor();\n }\n });\n \n toolsMenu.addSeparator();\n\n GUIUtils.addMenuItem(toolsMenu, \"XY List...\",\n \"Open position list manager window\",\n new Runnable() {\n public void run() {\n showXYPositionList();\n }\n },\n \"application_view_list.png\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Multi-Dimensional Acquisition...\",\n \"Open multi-dimensional acquisition setup window\",\n new Runnable() {\n public void run() {\n openAcqControlDialog();\n }\n },\n \"film.png\");\n \n \n centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu,\n \"Mouse Moves Stage (use Hand Tool)\",\n \"When enabled, double clicking or dragging in the snap/live\\n\"\n + \"window moves the XY-stage. Requires the hand tool.\",\n new Runnable() {\n public void run() {\n updateCenterAndDragListener();\n IJ.setTool(Toolbar.HAND);\n mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());\n }\n },\n mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));\n \n GUIUtils.addMenuItem(toolsMenu, \"Pixel Size Calibration...\",\n \"Define size calibrations specific to each objective lens. \"\n + \"When the objective in use has a calibration defined, \"\n + \"micromanager will automatically use it when \"\n + \"calculating metadata\",\n new Runnable() {\n public void run() {\n createCalibrationListDlg();\n }\n });\n /* \n GUIUtils.addMenuItem(toolsMenu, \"Image Processor Manager\",\n \"Control the order in which Image Processor plugins\"\n + \"are applied to incoming images.\",\n new Runnable() {\n public void run() {\n processorStackManager_.show();\n }\n });\n*/\n toolsMenu.addSeparator();\n\n GUIUtils.addMenuItem(toolsMenu, \"Hardware Configuration Wizard...\",\n \"Open wizard to create new hardware configuration\",\n new Runnable() {\n public void run() {\n runHardwareWizard();\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Load Hardware Configuration...\",\n \"Un-initialize current configuration and initialize new one\",\n new Runnable() {\n public void run() {\n loadConfiguration();\n initializeGUI();\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Reload Hardware Configuration\",\n \"Shutdown current configuration and initialize most recently loaded configuration\",\n new Runnable() {\n public void run() {\n loadSystemConfiguration();\n initializeGUI();\n }\n });\n\n \n for (int i=0; i<5; i++)\n {\n JMenuItem configItem = new JMenuItem();\n configItem.setText(Integer.toString(i));\n switchConfigurationMenu_.add(configItem);\n }\n \n switchConfigurationMenu_.setText(\"Switch Hardware Configuration\");\n toolsMenu.add(switchConfigurationMenu_);\n switchConfigurationMenu_.setToolTipText(\"Switch between recently used configurations\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Save Configuration Settings as...\",\n \"Save current configuration settings as new configuration file\",\n new Runnable() {\n public void run() {\n saveConfigPresets();\n updateChannelCombos();\n }\n });\n\n toolsMenu.addSeparator();\n\n final MMStudioMainFrame thisInstance = this;\n GUIUtils.addMenuItem(toolsMenu, \"Options...\",\n \"Set a variety of Micro-Manager configuration options\",\n new Runnable() {\n public void run() {\n final int oldBufsize = options_.circularBufferSizeMB_;\n\n OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,\n thisInstance);\n dlg.setVisible(true);\n // adjust memory footprint if necessary\n if (oldBufsize != options_.circularBufferSizeMB_) {\n try {\n core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);\n } catch (Exception exc) {\n ReportingUtils.showError(exc);\n }\n }\n }\n });\n }\n\n private void showRegistrationDialogMaybe() {\n // show registration dialog if not already registered\n // first check user preferences (for legacy compatibility reasons)\n boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,\n false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);\n\n if (!userReg) {\n boolean systemReg = systemPrefs_.getBoolean(\n RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);\n if (!systemReg) {\n // prompt for registration info\n RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);\n dlg.setVisible(true);\n }\n }\n }\n\n private void updateSwitchConfigurationMenu() {\n switchConfigurationMenu_.removeAll();\n for (final String configFile : MRUConfigFiles_) {\n if (!configFile.equals(sysConfigFile_)) {\n GUIUtils.addMenuItem(switchConfigurationMenu_,\n configFile, null,\n new Runnable() {\n public void run() {\n sysConfigFile_ = configFile;\n loadSystemConfiguration();\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n }\n });\n }\n }\n }\n\n\n \n public final void addLiveModeListener (LiveModeListener listener) {\n if (liveModeListeners_.contains(listener)) {\n return;\n }\n liveModeListeners_.add(listener);\n }\n \n public void removeLiveModeListener(LiveModeListener listener) {\n liveModeListeners_.remove(listener);\n }\n \n public void callLiveModeListeners(boolean enable) {\n for (LiveModeListener listener : liveModeListeners_) {\n listener.liveModeEnabled(enable);\n }\n }\n \n \n /**\n * Part of ScriptInterface\n * Manipulate acquisition so that it looks like a burst\n */\n public void runBurstAcquisition() throws MMScriptException {\n double interval = engine_.getFrameIntervalMs();\n int nr = engine_.getNumFrames();\n boolean doZStack = engine_.isZSliceSettingEnabled();\n boolean doChannels = engine_.isChannelsSettingEnabled();\n engine_.enableZSliceSetting(false);\n engine_.setFrames(nr, 0);\n engine_.enableChannelsSetting(false);\n try {\n engine_.acquire();\n } catch (MMException e) {\n throw new MMScriptException(e);\n }\n engine_.setFrames(nr, interval);\n engine_.enableZSliceSetting(doZStack);\n engine_.enableChannelsSetting(doChannels);\n }\n\n public void runBurstAcquisition(int nr) throws MMScriptException {\n int originalNr = engine_.getNumFrames();\n double interval = engine_.getFrameIntervalMs();\n engine_.setFrames(nr, 0);\n this.runBurstAcquisition();\n engine_.setFrames(originalNr, interval);\n }\n\n public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {\n String originalRoot = engine_.getRootName();\n engine_.setDirName(name);\n engine_.setRootName(root);\n this.runBurstAcquisition(nr);\n engine_.setRootName(originalRoot);\n }\n\n /**\n * @Deprecated\n * @throws MMScriptException\n */\n public void startBurstAcquisition() throws MMScriptException {\n runAcquisition();\n }\n\n public boolean isBurstAcquisitionRunning() throws MMScriptException {\n if (engine_ == null)\n return false;\n return engine_.isAcquisitionRunning();\n }\n\n private void startLoadingPipelineClass() {\n Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n acquisitionEngine2010LoadingThread_ = new Thread(\"Pipeline Class loading thread\") {\n @Override\n public void run() {\n try {\n acquisitionEngine2010Class_ = Class.forName(\"org.micromanager.AcquisitionEngine2010\");\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n acquisitionEngine2010Class_ = null;\n }\n }\n };\n acquisitionEngine2010LoadingThread_.start();\n }\n\n\n \n /**\n * Shows images as they appear in the default display window. Uses\n * the default processor stack to process images as they arrive on\n * the rawImageQueue.\n */\n public void runDisplayThread(BlockingQueue rawImageQueue, \n final DisplayImageRoutine displayImageRoutine) {\n final BlockingQueue processedImageQueue = \n ProcessorStack.run(rawImageQueue, \n getAcquisitionEngine().getImageProcessors());\n \n new Thread(\"Display thread\") {\n @Override\n public void run() {\n try {\n TaggedImage image;\n do {\n image = processedImageQueue.take();\n if (image != TaggedImageQueue.POISON) {\n displayImageRoutine.show(image);\n }\n } while (image != TaggedImageQueue.POISON);\n } catch (InterruptedException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }.start();\n }\n\n\n private static JLabel createLabel(String text, boolean big,\n JPanel parentPanel, int west, int north, int east, int south) {\n final JLabel label = new JLabel();\n label.setFont(new Font(\"Arial\",\n big ? Font.BOLD : Font.PLAIN,\n big ? 11 : 10));\n label.setText(text);\n GUIUtils.addWithEdges(parentPanel, label, west, north, east, south);\n return label;\n }\n\n public interface DisplayImageRoutine {\n public void show(TaggedImage image);\n }\n \n /**\n * used to store contrast settings to be later used for initialization of contrast of new windows.\n * Shouldn't be called by loaded data sets, only\n * ones that have been acquired\n */\n public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda, \n HistogramSettings settings) {\n String type = mda ? \"MDA_\" : \"SnapLive_\";\n if (options_.syncExposureMainAndMDA_) {\n type = \"\"; //only one group of contrast settings\n }\n contrastPrefs_.putInt(\"ContrastMin_\" + channelGroup + \"_\" + type + channel, settings.min_);\n contrastPrefs_.putInt(\"ContrastMax_\" + channelGroup + \"_\" + type + channel, settings.max_);\n contrastPrefs_.putDouble(\"ContrastGamma_\" + channelGroup + \"_\" + type + channel, settings.gamma_);\n contrastPrefs_.putInt(\"ContrastHistMax_\" + channelGroup + \"_\" + type + channel, settings.histMax_);\n contrastPrefs_.putInt(\"ContrastHistDisplayMode_\" + channelGroup + \"_\" + type + channel, settings.displayMode_);\n }\n\n public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) {\n String type = mda ? \"MDA_\" : \"SnapLive_\";\n if (options_.syncExposureMainAndMDA_) {\n type = \"\"; //only one group of contrast settings\n }\n return new HistogramSettings(\n contrastPrefs_.getInt(\"ContrastMin_\" + channelGroup + \"_\" + type + channel,0),\n contrastPrefs_.getInt(\"ContrastMax_\" + channelGroup + \"_\" + type + channel, 65536),\n contrastPrefs_.getDouble(\"ContrastGamma_\" + channelGroup + \"_\" + type + channel, 1.0),\n contrastPrefs_.getInt(\"ContrastHistMax_\" + channelGroup + \"_\" + type + channel, -1),\n contrastPrefs_.getInt(\"ContrastHistDisplayMode_\" + channelGroup + \"_\" + type + channel, 1) );\n }\n\n private void setExposure() {\n try {\n if (!isLiveModeOn()) {\n core_.setExposure(NumberUtils.displayStringToDouble(\n textFieldExp_.getText()));\n } else {\n liveModeTimer_.stop();\n core_.setExposure(NumberUtils.displayStringToDouble(\n textFieldExp_.getText()));\n try {\n liveModeTimer_.begin();\n } catch (Exception e) {\n ReportingUtils.showError(\"Couldn't restart live mode\");\n liveModeTimer_.stop();\n }\n }\n \n\n // Display the new exposure time\n double exposure = core_.getExposure();\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));\n \n // update current channel in MDA window with this exposure\n String channelGroup = core_.getChannelGroup();\n String channel = core_.getCurrentConfigFromCache(channelGroup);\n if (!channel.equals(\"\") ) {\n exposurePrefs_.putDouble(\"Exposure_\" + channelGroup + \"_\"\n + channel, exposure);\n if (options_.syncExposureMainAndMDA_) {\n getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure);\n }\n }\n \n\n } catch (Exception exp) {\n // Do nothing.\n }\n }\n \n\n\n public double getPreferredWindowMag() {\n return options_.windowMag_;\n }\n\n public boolean getMetadataFileWithMultipageTiff() {\n return options_.mpTiffMetadataFile_;\n }\n\n public boolean getSeparateFilesForPositionsMPTiff() {\n return options_.mpTiffSeparateFilesForPositions_;\n }\n \n @Override\n public boolean getHideMDADisplayOption() {\n return options_.hideMDADisplay_;\n }\n\n private void updateTitle() {\n this.setTitle(MICRO_MANAGER_TITLE + \" \" + MMVersion.VERSION_STRING + \" - \" + sysConfigFile_);\n }\n\n public void updateLineProfile() {\n if (WindowManager.getCurrentWindow() == null || profileWin_ == null\n || !profileWin_.isShowing()) {\n return;\n }\n\n calculateLineProfileData(WindowManager.getCurrentImage());\n profileWin_.setData(lineProfileData_);\n }\n\n private void openLineProfileWindow() {\n if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {\n return;\n }\n calculateLineProfileData(WindowManager.getCurrentImage());\n if (lineProfileData_ == null) {\n return;\n }\n profileWin_ = new GraphFrame();\n profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n profileWin_.setData(lineProfileData_);\n profileWin_.setAutoScale();\n profileWin_.setTitle(\"Live line profile\");\n profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(profileWin_);\n profileWin_.setVisible(true);\n }\n\n @Override\n public Rectangle getROI() throws MMScriptException {\n // ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):\n int[][] a = new int[4][1];\n try {\n core_.getROI(a[0], a[1], a[2], a[3]);\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n // Return as a single array with x,y,w,h:\n return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);\n }\n\n private void calculateLineProfileData(ImagePlus imp) {\n // generate line profile\n Roi roi = imp.getRoi();\n if (roi == null || !roi.isLine()) {\n\n // if there is no line ROI, create one\n Rectangle r = imp.getProcessor().getRoi();\n int iWidth = r.width;\n int iHeight = r.height;\n int iXROI = r.x;\n int iYROI = r.y;\n if (roi == null) {\n iXROI += iWidth / 2;\n iYROI += iHeight / 2;\n }\n\n roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI\n + iWidth / 4, iYROI + iHeight / 4);\n imp.setRoi(roi);\n roi = imp.getRoi();\n }\n\n ImageProcessor ip = imp.getProcessor();\n ip.setInterpolate(true);\n Line line = (Line) roi;\n\n if (lineProfileData_ == null) {\n lineProfileData_ = new GraphData();\n }\n lineProfileData_.setData(line.getPixels());\n }\n\n \n\n private void setROI() {\n ImagePlus curImage = WindowManager.getCurrentImage();\n if (curImage == null) {\n return;\n }\n\n Roi roi = curImage.getRoi();\n \n try {\n if (roi == null) {\n // if there is no ROI, create one\n Rectangle r = curImage.getProcessor().getRoi();\n int iWidth = r.width;\n int iHeight = r.height;\n int iXROI = r.x;\n int iYROI = r.y;\n if (roi == null) {\n iWidth /= 2;\n iHeight /= 2;\n iXROI += iWidth / 2;\n iYROI += iHeight / 2;\n }\n\n curImage.setRoi(iXROI, iYROI, iWidth, iHeight);\n roi = curImage.getRoi();\n }\n\n if (roi.getType() != Roi.RECTANGLE) {\n handleError(\"ROI must be a rectangle.\\nUse the ImageJ rectangle tool to draw the ROI.\");\n return;\n }\n\n Rectangle r = roi.getBounds();\n // if we already had an ROI defined, correct for the offsets\n Rectangle cameraR = getROI();\n r.x += cameraR.x;\n r.y += cameraR.y;\n // Stop (and restart) live mode if it is running\n setROI(r);\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n private void clearROI() {\n try {\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n core_.clearROI();\n updateStaticInfo();\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n /**\n * Returns instance of the core uManager object;\n */\n @Override\n public CMMCore getMMCore() {\n return core_;\n }\n\n /**\n * Returns singleton instance of MMStudioMainFrame\n */\n public static MMStudioMainFrame getInstance() {\n return gui_;\n }\n\n public MetadataPanel getMetadataPanel() {\n return metadataPanel_;\n }\n\n public final void setExitStrategy(boolean closeOnExit) {\n if (closeOnExit) {\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n else {\n setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n }\n }\n\n @Override\n public void saveConfigPresets() {\n MicroscopeModel model = new MicroscopeModel();\n try {\n model.loadFromFile(sysConfigFile_);\n model.createSetupConfigsFromHardware(core_);\n model.createResolutionsFromHardware(core_);\n File f = FileDialogs.save(this, \"Save the configuration file\", MM_CONFIG_FILE);\n if (f != null) {\n model.saveToFile(f.getAbsolutePath());\n sysConfigFile_ = f.getAbsolutePath();\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n configChanged_ = false;\n setConfigSaveButtonStatus(configChanged_);\n updateTitle();\n }\n } catch (MMConfigFileException e) {\n ReportingUtils.showError(e);\n }\n }\n\n protected void setConfigSaveButtonStatus(boolean changed) {\n saveConfigButton_.setEnabled(changed);\n }\n\n public String getAcqDirectory() {\n return openAcqDirectory_;\n }\n \n /**\n * Get currently used configuration file\n * @return - Path to currently used configuration file\n */\n public String getSysConfigFile() {\n return sysConfigFile_;\n }\n\n public void setAcqDirectory(String dir) {\n openAcqDirectory_ = dir;\n }\n\n /**\n * Open an existing acquisition directory and build viewer window.\n *\n */\n public void openAcquisitionData(boolean inRAM) {\n\n // choose the directory\n // --------------------\n File f = FileDialogs.openDir(this, \"Please select an image data set\", MM_DATA_SET);\n if (f != null) {\n if (f.isDirectory()) {\n openAcqDirectory_ = f.getAbsolutePath();\n } else {\n openAcqDirectory_ = f.getParent();\n }\n String acq = null;\n try {\n acq = openAcquisitionData(openAcqDirectory_, inRAM);\n } catch (MMScriptException ex) {\n ReportingUtils.showError(ex);\n } finally {\n try {\n acqMgr_.closeAcquisition(acq);\n } catch (MMScriptException ex) {\n ReportingUtils.logError(ex);\n }\n }\n \n }\n }\n\n @Override\n public String openAcquisitionData(String dir, boolean inRAM, boolean show) \n throws MMScriptException {\n String rootDir = new File(dir).getAbsolutePath();\n String name = new File(dir).getName();\n rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1));\n name = acqMgr_.getUniqueAcquisitionName(name);\n acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true);\n try {\n getAcquisition(name).initialize();\n } catch (MMScriptException mex) {\n acqMgr_.closeAcquisition(name);\n throw (mex);\n }\n \n return name;\n }\n\n /**\n * Opens an existing data set. Shows the acquisition in a window.\n * @return The acquisition object.\n */\n @Override\n public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException {\n return openAcquisitionData(dir, inRam, true);\n }\n\n protected void zoomOut() {\n ImageWindow curWin = WindowManager.getCurrentWindow();\n if (curWin != null) {\n ImageCanvas canvas = curWin.getCanvas();\n Rectangle r = canvas.getBounds();\n canvas.zoomOut(r.width / 2, r.height / 2);\n\n VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());\n if (vad != null) {\n vad.storeWindowSizeAfterZoom(curWin);\n vad.updateWindowTitleAndStatus();\n }\n }\n }\n\n protected void zoomIn() {\n ImageWindow curWin = WindowManager.getCurrentWindow();\n if (curWin != null) {\n ImageCanvas canvas = curWin.getCanvas();\n Rectangle r = canvas.getBounds();\n canvas.zoomIn(r.width / 2, r.height / 2);\n \n VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());\n if (vad != null) {\n vad.storeWindowSizeAfterZoom(curWin);\n vad.updateWindowTitleAndStatus();\n } \n }\n }\n\n protected void changeBinning() {\n try {\n boolean liveRunning = false;\n if (isLiveModeOn() ) {\n liveRunning = true;\n enableLiveMode(false);\n } \n \n if (isCameraAvailable()) {\n Object item = comboBinning_.getSelectedItem();\n if (item != null) {\n core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());\n }\n }\n updateStaticInfo();\n\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n\n \n }\n\n private void createPropertyEditor() {\n if (propertyBrowser_ != null) {\n propertyBrowser_.dispose();\n }\n\n propertyBrowser_ = new PropertyEditor();\n propertyBrowser_.setGui(this);\n propertyBrowser_.setVisible(true);\n propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n propertyBrowser_.setCore(core_);\n }\n\n private void createCalibrationListDlg() {\n if (calibrationListDlg_ != null) {\n calibrationListDlg_.dispose();\n }\n\n calibrationListDlg_ = new CalibrationListDlg(core_);\n calibrationListDlg_.setVisible(true);\n calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n calibrationListDlg_.setParentGUI(this);\n }\n\n public CalibrationListDlg getCalibrationListDlg() {\n if (calibrationListDlg_ == null) {\n createCalibrationListDlg();\n }\n return calibrationListDlg_;\n }\n\n private void createScriptPanel() {\n if (scriptPanel_ == null) {\n scriptPanel_ = new ScriptPanel(core_, options_, this);\n scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);\n scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);\n scriptPanel_.setParentGUI(this);\n scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(scriptPanel_);\n }\n }\n\n private void createPipelinePanel() {\n if (pipelinePanel_ == null) {\n pipelinePanel_ = new PipelinePanel(this, engine_);\n pipelinePanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(pipelinePanel_);\n }\n }\n\n /**\n * Updates Status line in main window from cached values\n */\n private void updateStaticInfoFromCache() {\n String dimText = \"Image info (from camera): \" + staticInfo_.width_ + \" X \" + staticInfo_.height_ + \" X \"\n + staticInfo_.bytesPerPixel_ + \", Intensity range: \" + staticInfo_.imageBitDepth_ + \" bits\";\n dimText += \", \" + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + \"nm/pix\";\n if (zStageLabel_.length() > 0) {\n dimText += \", Z=\" + TextUtils.FMT2.format(staticInfo_.zPos_) + \"um\";\n }\n if (xyStageLabel_.length() > 0) {\n dimText += \", XY=(\" + TextUtils.FMT2.format(staticInfo_.x_) + \",\" + TextUtils.FMT2.format(staticInfo_.y_) + \")um\";\n }\n\n labelImageDimensions_.setText(dimText);\n }\n\n public void updateXYPos(double x, double y) {\n staticInfo_.x_ = x;\n staticInfo_.y_ = y;\n\n updateStaticInfoFromCache();\n }\n\n public void updateZPos(double z) {\n staticInfo_.zPos_ = z;\n\n updateStaticInfoFromCache();\n }\n\n public void updateXYPosRelative(double x, double y) {\n staticInfo_.x_ += x;\n staticInfo_.y_ += y;\n\n updateStaticInfoFromCache();\n }\n\n public void updateZPosRelative(double z) {\n staticInfo_.zPos_ += z;\n\n updateStaticInfoFromCache();\n }\n\n public void updateXYStagePosition(){\n\n double x[] = new double[1];\n double y[] = new double[1];\n try {\n if (xyStageLabel_.length() > 0) \n core_.getXYPosition(xyStageLabel_, x, y);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n\n staticInfo_.x_ = x[0];\n staticInfo_.y_ = y[0];\n updateStaticInfoFromCache();\n }\n\n private void updatePixSizeUm (double pixSizeUm) {\n staticInfo_.pixSizeUm_ = pixSizeUm;\n\n updateStaticInfoFromCache();\n }\n\n private void updateStaticInfo() {\n double zPos = 0.0;\n double x[] = new double[1];\n double y[] = new double[1];\n\n try {\n if (zStageLabel_.length() > 0) {\n zPos = core_.getPosition(zStageLabel_);\n }\n if (xyStageLabel_.length() > 0) {\n core_.getXYPosition(xyStageLabel_, x, y);\n }\n } catch (Exception e) {\n handleException(e);\n }\n\n staticInfo_.width_ = core_.getImageWidth();\n staticInfo_.height_ = core_.getImageHeight();\n staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();\n staticInfo_.imageBitDepth_ = core_.getImageBitDepth();\n staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();\n staticInfo_.zPos_ = zPos;\n staticInfo_.x_ = x[0];\n staticInfo_.y_ = y[0];\n\n updateStaticInfoFromCache();\n }\n\n public void toggleShutter() {\n try {\n if (!toggleShutterButton_.isEnabled())\n return;\n toggleShutterButton_.requestFocusInWindow();\n if (toggleShutterButton_.getText().equals(\"Open\")) {\n setShutterButton(true);\n core_.setShutterOpen(true);\n } else {\n core_.setShutterOpen(false);\n setShutterButton(false);\n }\n } catch (Exception e1) {\n ReportingUtils.showError(e1);\n }\n }\n\n private void updateCenterAndDragListener() {\n if (centerAndDragMenuItem_.isSelected()) {\n centerAndDragListener_.start();\n } else {\n centerAndDragListener_.stop();\n }\n }\n \n private void setShutterButton(boolean state) {\n if (state) {\n toggleShutterButton_.setText(\"Close\");\n } else {\n toggleShutterButton_.setText(\"Open\");\n }\n }\n \n \n private void checkPosListDlg() {\n if (posListDlg_ == null) {\n posListDlg_ = new PositionListDlg(core_, this, posList_, \n acqControlWin_,options_);\n GUIUtils.recallPosition(posListDlg_);\n posListDlg_.setBackground(gui_.getBackgroundColor());\n gui_.addMMBackgroundListener(posListDlg_);\n posListDlg_.addListeners();\n }\n }\n \n\n // //////////////////////////////////////////////////////////////////////////\n // public interface available for scripting access\n // //////////////////////////////////////////////////////////////////////////\n @Override\n public void snapSingleImage() {\n doSnap();\n }\n\n public Object getPixels() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null) {\n return ip.getProcessor().getPixels();\n }\n\n return null;\n }\n\n public void setPixels(Object obj) {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip == null) {\n return;\n }\n ip.getProcessor().setPixels(obj);\n }\n\n public int getImageHeight() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getHeight();\n return 0;\n }\n\n public int getImageWidth() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getWidth();\n return 0;\n }\n\n public int getImageDepth() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getBitDepth();\n return 0;\n }\n\n public ImageProcessor getImageProcessor() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip == null)\n return null;\n return ip.getProcessor();\n }\n\n private boolean isCameraAvailable() {\n return cameraLabel_.length() > 0;\n }\n\n /**\n * Part of ScriptInterface API\n * Opens the XYPositionList when it is not opened\n * Adds the current position to the list (same as pressing the \"Mark\" button)\n */\n @Override\n public void markCurrentPosition() {\n if (posListDlg_ == null) {\n showXYPositionList();\n }\n if (posListDlg_ != null) {\n posListDlg_.markPosition();\n }\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n @Deprecated\n public AcqControlDlg getAcqDlg() {\n return acqControlWin_;\n }\n\n \n /**\n * Implements ScriptInterface\n */\n @Override\n @Deprecated\n public PositionListDlg getXYPosListDlg() {\n checkPosListDlg();\n return posListDlg_;\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n public boolean isAcquisitionRunning() {\n if (engine_ == null)\n return false;\n return engine_.isAcquisitionRunning();\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n public boolean versionLessThan(String version) throws MMScriptException {\n try {\n String[] v = MMVersion.VERSION_STRING.split(\" \", 2);\n String[] m = v[0].split(\"\\\\.\", 3);\n String[] v2 = version.split(\" \", 2);\n String[] m2 = v2[0].split(\"\\\\.\", 3);\n for (int i=0; i < 3; i++) {\n if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return true;\n }\n if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {\n return false;\n }\n }\n if (v2.length < 2 || v2[1].equals(\"\") )\n return false;\n if (v.length < 2 ) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return true;\n }\n if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return false;\n }\n return true;\n\n } catch (Exception ex) {\n throw new MMScriptException (\"Format of version String should be \\\"a.b.c\\\"\");\n }\n } \n\n @Override\n public boolean isLiveModeOn() {\n return liveModeTimer_ != null && liveModeTimer_.isRunning();\n }\n \n public LiveModeTimer getLiveModeTimer() {\n if (liveModeTimer_ == null) {\n liveModeTimer_ = new LiveModeTimer();\n }\n return liveModeTimer_;\n }\n \n \n\n public void updateButtonsForLiveMode(boolean enable) {\n autoShutterCheckBox_.setEnabled(!enable);\n if (core_.getAutoShutter()) {\n toggleShutterButton_.setText(enable ? \"Close\" : \"Open\" );\n }\n snapButton_.setEnabled(!enable);\n //toAlbumButton_.setEnabled(!enable);\n liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,\n \"/org/micromanager/icons/cancel.png\")\n : SwingResourceManager.getIcon(MMStudioMainFrame.class,\n \"/org/micromanager/icons/camera_go.png\"));\n liveButton_.setSelected(false);\n liveButton_.setText(enable ? \"Stop Live\" : \"Live\");\n \n }\n\n public boolean getLiveMode() {\n return isLiveModeOn();\n }\n\n public boolean updateImage() {\n try {\n if (isLiveModeOn()) {\n enableLiveMode(false);\n return true; // nothing to do, just show the last image\n }\n\n if (WindowManager.getCurrentWindow() == null) {\n return false;\n }\n\n ImagePlus ip = WindowManager.getCurrentImage();\n \n core_.snapImage();\n Object img = core_.getImage();\n\n ip.getProcessor().setPixels(img);\n ip.updateAndRepaintWindow();\n\n if (!isCurrentImageFormatSupported()) {\n return false;\n }\n \n updateLineProfile();\n } catch (Exception e) {\n ReportingUtils.showError(e);\n return false;\n }\n\n return true;\n }\n\n public boolean displayImage(final Object pixels) {\n if (pixels instanceof TaggedImage) {\n return displayTaggedImage((TaggedImage) pixels, true);\n } else {\n return displayImage(pixels, true);\n }\n }\n\n\n public boolean displayImage(final Object pixels, boolean wait) {\n checkSimpleAcquisition();\n try { \n int width = getAcquisition(SIMPLE_ACQ).getWidth();\n int height = getAcquisition(SIMPLE_ACQ).getHeight();\n int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth(); \n TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth);\n simpleDisplay_.getImageCache().putImage(ti);\n simpleDisplay_.showImage(ti, wait);\n return true;\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n return false;\n }\n }\n\n public boolean displayImageWithStatusLine(Object pixels, String statusLine) {\n boolean ret = displayImage(pixels);\n simpleDisplay_.displayStatusLine(statusLine);\n return ret;\n }\n\n public void displayStatusLine(String statusLine) {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) {\n return;\n }\n VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine);\n }\n\n private boolean isCurrentImageFormatSupported() {\n boolean ret = false;\n long channels = core_.getNumberOfComponents();\n long bpp = core_.getBytesPerPixel();\n\n if (channels > 1 && channels != 4 && bpp != 1) {\n handleError(\"Unsupported image format.\");\n } else {\n ret = true;\n }\n return ret;\n }\n\n public void doSnap() {\n doSnap(false);\n }\n\n public void doSnap(final boolean album) {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n\n BlockingQueue snapImageQueue = \n new LinkedBlockingQueue();\n \n try {\n core_.snapImage();\n long c = core_.getNumberOfCameraChannels();\n runDisplayThread(snapImageQueue, new DisplayImageRoutine() {\n @Override\n public void show(final TaggedImage image) {\n if (album) {\n try {\n addToAlbum(image);\n } catch (MMScriptException ex) {\n ReportingUtils.showError(ex);\n }\n } else {\n displayImage(image);\n }\n }\n\n });\n \n for (int i = 0; i < c; ++i) {\n TaggedImage img = core_.getTaggedImage(i);\n img.tags.put(\"Channels\", c);\n snapImageQueue.put(img);\n }\n \n snapImageQueue.put(TaggedImageQueue.POISON);\n\n if (simpleDisplay_ != null) {\n ImagePlus imgp = simpleDisplay_.getImagePlus();\n if (imgp != null) {\n ImageWindow win = imgp.getWindow();\n if (win != null) {\n win.toFront();\n }\n }\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n /**\n * Is this function still needed? It does some magic with tags. I found \n * it to do harmful thing with tags when a Multi-Camera device is\n * present (that issue is now fixed).\n */\n public void normalizeTags(TaggedImage ti) {\n if (ti != TaggedImageQueue.POISON) {\n int channel = 0;\n try {\n\n if (ti.tags.has(\"ChannelIndex\")) {\n channel = MDUtils.getChannelIndex(ti.tags);\n }\n MDUtils.setChannelIndex(ti.tags, channel);\n MDUtils.setPositionIndex(ti.tags, 0);\n MDUtils.setSliceIndex(ti.tags, 0);\n MDUtils.setFrameIndex(ti.tags, 0);\n \n } catch (JSONException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }\n\n private boolean displayTaggedImage(TaggedImage ti, boolean update) {\n try {\n checkSimpleAcquisition(ti);\n setCursor(new Cursor(Cursor.WAIT_CURSOR));\n ti.tags.put(\"Summary\", getAcquisition(SIMPLE_ACQ).getSummaryMetadata());\n addStagePositionToTags(ti);\n addImage(SIMPLE_ACQ, ti, update, true);\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n return false;\n }\n if (update) {\n setCursor(new Cursor(Cursor.DEFAULT_CURSOR));\n updateLineProfile();\n }\n return true;\n }\n \n public void addStagePositionToTags(TaggedImage ti) throws JSONException {\n if (gui_.xyStageLabel_.length() > 0) {\n ti.tags.put(\"XPositionUm\", gui_.staticInfo_.x_);\n ti.tags.put(\"YPositionUm\", gui_.staticInfo_.y_);\n }\n if (gui_.zStageLabel_.length() > 0) {\n ti.tags.put(\"ZPositionUm\", gui_.staticInfo_.zPos_);\n }\n }\n\n private void configureBinningCombo() throws Exception {\n if (cameraLabel_.length() > 0) {\n ActionListener[] listeners;\n\n // binning combo\n if (comboBinning_.getItemCount() > 0) {\n comboBinning_.removeAllItems();\n }\n StrVector binSizes = core_.getAllowedPropertyValues(\n cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n listeners = comboBinning_.getActionListeners();\n for (int i = 0; i < listeners.length; i++) {\n comboBinning_.removeActionListener(listeners[i]);\n }\n for (int i = 0; i < binSizes.size(); i++) {\n comboBinning_.addItem(binSizes.get(i));\n }\n\n comboBinning_.setMaximumRowCount((int) binSizes.size());\n if (binSizes.isEmpty()) {\n comboBinning_.setEditable(true);\n } else {\n comboBinning_.setEditable(false);\n }\n\n for (int i = 0; i < listeners.length; i++) {\n comboBinning_.addActionListener(listeners[i]);\n }\n }\n }\n\n public void initializeGUI() {\n try {\n\n // establish device roles\n cameraLabel_ = core_.getCameraDevice();\n shutterLabel_ = core_.getShutterDevice();\n zStageLabel_ = core_.getFocusDevice();\n xyStageLabel_ = core_.getXYStageDevice();\n engine_.setZStageDevice(zStageLabel_); \n \n configureBinningCombo();\n\n // active shutter combo\n try {\n shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n\n if (shutters_ != null) {\n String items[] = new String[(int) shutters_.size()];\n for (int i = 0; i < shutters_.size(); i++) {\n items[i] = shutters_.get(i);\n }\n\n GUIUtils.replaceComboContents(shutterComboBox_, items);\n String activeShutter = core_.getShutterDevice();\n if (activeShutter != null) {\n shutterComboBox_.setSelectedItem(activeShutter);\n } else {\n shutterComboBox_.setSelectedItem(\"\");\n }\n }\n\n // Autofocus\n autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null);\n autofocusNowButton_.setEnabled(afMgr_.getDevice() != null);\n\n // Rebuild stage list in XY PositinList\n if (posListDlg_ != null) {\n posListDlg_.rebuildAxisList();\n }\n\n updateGUI(true);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n\n \n /**\n * Adds plugin_ items to the plugins menu\n * Adds submenus (currently only 1 level deep)\n * @param plugin_ - plugin_ to be added to the menu\n */\n public void addPluginToMenu(final PluginLoader.PluginItem plugin) {\n List path = plugin.getMenuPath();\n if (path.size() == 1) {\n GUIUtils.addMenuItem(pluginMenu_, plugin.getMenuItem(), plugin.getTooltip(),\n new Runnable() {\n public void run() {\n displayPlugin(plugin);\n }\n });\n }\n if (path.size() == 2) {\n if (pluginSubMenus_ == null) {\n pluginSubMenus_ = new HashMap();\n }\n String groupName = path.get(0);\n JMenu submenu = pluginSubMenus_.get(groupName);\n if (submenu == null) {\n submenu = new JMenu(groupName);\n pluginSubMenus_.put(groupName, submenu);\n submenu.validate();\n pluginMenu_.add(submenu);\n }\n GUIUtils.addMenuItem(submenu, plugin.getMenuItem(), plugin.getTooltip(),\n new Runnable() {\n public void run() {\n displayPlugin(plugin);\n }\n });\n }\n \n pluginMenu_.validate();\n menuBar_.validate();\n }\n\n // Handle a plugin being selected from the Plugins menu.\n private static void displayPlugin(final PluginLoader.PluginItem plugin) {\n ReportingUtils.logMessage(\"Plugin command: \" + plugin.getMenuItem());\n plugin.instantiate();\n switch (plugin.getPluginType()) {\n case PLUGIN_STANDARD:\n // Standard plugin; create its UI.\n ((MMPlugin) plugin.getPlugin()).show();\n break;\n case PLUGIN_PROCESSOR:\n // Processor plugin; check for existing processor of \n // this type and show its UI if applicable; otherwise\n // create a new one.\n MMProcessorPlugin procPlugin = (MMProcessorPlugin) plugin.getPlugin();\n String procName = PluginLoader.getNameForPluginClass(procPlugin.getClass());\n DataProcessor pipelineProcessor = gui_.engine_.getProcessorRegisteredAs(procName);\n if (pipelineProcessor == null) {\n // No extant processor of this type; make a new one,\n // which automatically adds it to the pipeline.\n pipelineProcessor = gui_.engine_.makeProcessor(procName, gui_);\n }\n if (pipelineProcessor != null) {\n // Show the GUI for this processor. The extra null check is \n // because making the processor (above) could have failed.\n pipelineProcessor.makeConfigurationGUI();\n }\n break;\n default:\n // Unrecognized plugin type; just skip it. \n ReportingUtils.logError(\"Unrecognized plugin type \" + plugin.getPluginType());\n }\n }\n \n public void updateGUI(boolean updateConfigPadStructure) {\n updateGUI(updateConfigPadStructure, false);\n }\n\n public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) {\n\n try {\n // establish device roles\n cameraLabel_ = core_.getCameraDevice();\n shutterLabel_ = core_.getShutterDevice();\n zStageLabel_ = core_.getFocusDevice();\n xyStageLabel_ = core_.getXYStageDevice();\n\n afMgr_.refresh();\n\n // camera settings\n if (isCameraAvailable()) {\n double exp = core_.getExposure();\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));\n configureBinningCombo();\n String binSize;\n if (fromCache) {\n binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n } else {\n binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n }\n GUIUtils.setComboSelection(comboBinning_, binSize);\n }\n\n if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {\n autoShutterCheckBox_.setSelected(core_.getAutoShutter());\n boolean shutterOpen = core_.getShutterOpen();\n setShutterButton(shutterOpen);\n if (autoShutterCheckBox_.isSelected()) {\n toggleShutterButton_.setEnabled(false);\n } else {\n toggleShutterButton_.setEnabled(true);\n }\n }\n\n // active shutter combo\n if (shutters_ != null) {\n String activeShutter = core_.getShutterDevice();\n if (activeShutter != null) {\n shutterComboBox_.setSelectedItem(activeShutter);\n } else {\n shutterComboBox_.setSelectedItem(\"\");\n }\n }\n\n // state devices\n if (updateConfigPadStructure && (configPad_ != null)) {\n configPad_.refreshStructure(fromCache);\n // Needed to update read-only properties. May slow things down...\n if (!fromCache)\n core_.updateSystemStateCache();\n }\n\n // update Channel menus in Multi-dimensional acquisition dialog\n updateChannelCombos();\n\n // update list of pixel sizes in pixel size configuration window\n if (calibrationListDlg_ != null) {\n calibrationListDlg_.refreshCalibrations();\n }\n if (propertyBrowser_ != null) {\n propertyBrowser_.refresh();\n }\n\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n\n updateStaticInfo();\n updateTitle();\n\n }\n\n //TODO: Deprecated @Override\n public boolean okToAcquire() {\n return !isLiveModeOn();\n }\n\n //TODO: Deprecated @Override\n public void stopAllActivity() {\n if (this.acquisitionEngine2010_ != null) {\n this.acquisitionEngine2010_.stop();\n }\n enableLiveMode(false);\n }\n\n /**\n * Cleans up resources while shutting down \n * \n * @param calledByImageJ\n * @return flag indicating success. Shut down should abort when flag is false \n */\n private boolean cleanupOnClose(boolean calledByImageJ) {\n // Save config presets if they were changed.\n if (configChanged_) {\n Object[] options = {\"Yes\", \"No\"};\n int n = JOptionPane.showOptionDialog(null,\n \"Save Changed Configuration?\", \"Micro-Manager\",\n JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,\n null, options, options[0]);\n if (n == JOptionPane.YES_OPTION) {\n saveConfigPresets();\n // if the configChanged_ flag did not become false, the user \n // must have cancelled the configuration saving and we should cancel\n // quitting as well\n if (configChanged_) {\n return false;\n }\n }\n }\n if (liveModeTimer_ != null)\n liveModeTimer_.stop();\n \n // check needed to avoid deadlock\n if (!calledByImageJ) {\n if (!WindowManager.closeAllWindows()) {\n core_.logMessage(\"Failed to close some windows\");\n }\n }\n\n if (profileWin_ != null) {\n removeMMBackgroundListener(profileWin_);\n profileWin_.dispose();\n }\n\n if (scriptPanel_ != null) {\n removeMMBackgroundListener(scriptPanel_);\n scriptPanel_.closePanel();\n }\n\n if (pipelinePanel_ != null) {\n removeMMBackgroundListener(pipelinePanel_);\n pipelinePanel_.dispose();\n }\n\n if (propertyBrowser_ != null) {\n removeMMBackgroundListener(propertyBrowser_);\n propertyBrowser_.dispose();\n }\n\n if (acqControlWin_ != null) {\n removeMMBackgroundListener(acqControlWin_);\n acqControlWin_.close();\n }\n\n if (engine_ != null) {\n engine_.shutdown();\n }\n\n if (afMgr_ != null) {\n afMgr_.closeOptionsDialog();\n }\n\n engine_.disposeProcessors();\n\n pluginLoader_.disposePlugins();\n\n synchronized (shutdownLock_) {\n try {\n if (core_ != null) {\n ReportingUtils.setCore(null);\n core_.delete();\n core_ = null;\n }\n } catch (Exception err) {\n ReportingUtils.showError(err);\n }\n }\n return true;\n }\n\n private void saveSettings() {\n Rectangle r = this.getBounds();\n\n mainPrefs_.putInt(MAIN_FRAME_X, r.x);\n mainPrefs_.putInt(MAIN_FRAME_Y, r.y);\n mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);\n mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);\n mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());\n \n mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);\n mainPrefs_.put(MAIN_SAVE_METHOD, \n ImageUtils.getImageStorageClass().getName());\n\n // save field values from the main window\n // NOTE: automatically restoring these values on startup may cause\n // problems\n mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());\n\n // NOTE: do not save auto shutter state\n\n if (afMgr_ != null && afMgr_.getDevice() != null) {\n mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());\n }\n }\n\n private void loadConfiguration() {\n File f = FileDialogs.openFile(this, \"Load a config file\",MM_CONFIG_FILE);\n if (f != null) {\n sysConfigFile_ = f.getAbsolutePath();\n configChanged_ = false;\n setConfigSaveButtonStatus(configChanged_);\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n loadSystemConfiguration();\n }\n }\n\n\n public synchronized boolean closeSequence(boolean calledByImageJ) {\n\n if (!this.isRunning()) {\n if (core_ != null) {\n core_.logMessage(\"MMStudioMainFrame::closeSequence called while running_ is false\");\n }\n return true;\n }\n \n if (engine_ != null && engine_.isAcquisitionRunning()) {\n int result = JOptionPane.showConfirmDialog(\n this,\n \"Acquisition in progress. Are you sure you want to exit and discard all data?\",\n \"Micro-Manager\", JOptionPane.YES_NO_OPTION,\n JOptionPane.INFORMATION_MESSAGE);\n\n if (result == JOptionPane.NO_OPTION) {\n return false;\n }\n }\n\n stopAllActivity();\n \n try {\n // Close all image windows associated with MM. Canceling saving of \n // any of these should abort shutdown\n if (!acqMgr_.closeAllImageWindows()) {\n return false;\n }\n } catch (MMScriptException ex) {\n // Not sure what to do here...\n }\n\n if (!cleanupOnClose(calledByImageJ)) {\n return false;\n }\n\n running_ = false;\n\n saveSettings();\n try {\n configPad_.saveSettings();\n options_.saveSettings();\n hotKeys_.saveSettings();\n } catch (NullPointerException e) {\n if (core_ != null)\n this.logError(e);\n } \n // disposing sometimes hangs ImageJ!\n // this.dispose();\n if (options_.closeOnExit_) {\n if (!runsAsPlugin_) {\n System.exit(0);\n } else {\n ImageJ ij = IJ.getInstance();\n if (ij != null) {\n ij.quit();\n }\n }\n } else {\n this.dispose();\n }\n \n return true;\n }\n\n /*\n public void applyContrastSettings(ContrastSettings contrast8,\n ContrastSettings contrast16) {\n ImagePlus img = WindowManager.getCurrentImage();\n if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null )\n return;\n if (img.getBytesPerPixel() == 1) \n VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,\n contrast8.min, contrast8.max, contrast8.gamma);\n else\n VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, \n contrast16.min, contrast16.max, contrast16.gamma);\n }\n */\n\n //TODO: Deprecated @Override\n public ContrastSettings getContrastSettings() {\n ImagePlus img = WindowManager.getCurrentImage();\n if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null )\n return null;\n return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0);\n }\n \n/*\n public boolean is16bit() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null && ip.getProcessor() instanceof ShortProcessor) {\n return true;\n }\n return false;\n }\n * */\n\n public boolean isRunning() {\n return running_;\n }\n\n /**\n * Executes the beanShell script. This script instance only supports\n * commands directed to the core object.\n */\n private void executeStartupScript() {\n // execute startup script\n File f = new File(startupScriptFile_);\n\n if (startupScriptFile_.length() > 0 && f.exists()) {\n WaitDialog waitDlg = new WaitDialog(\n \"Executing startup script, please wait...\");\n waitDlg.showDialog();\n Interpreter interp = new Interpreter();\n try {\n // insert core object only\n interp.set(SCRIPT_CORE_OBJECT, core_);\n interp.set(SCRIPT_ACQENG_OBJECT, engine_);\n interp.set(SCRIPT_GUI_OBJECT, this);\n\n // read text file and evaluate\n interp.eval(TextUtils.readTextFile(startupScriptFile_));\n } catch (IOException exc) {\n ReportingUtils.logError(exc, \"Unable to read the startup script (\" + startupScriptFile_ + \").\");\n } catch (EvalError exc) {\n ReportingUtils.logError(exc);\n } finally {\n waitDlg.closeDialog();\n }\n } else {\n if (startupScriptFile_.length() > 0)\n ReportingUtils.logMessage(\"Startup script file (\"+startupScriptFile_+\") not present.\");\n }\n }\n\n /**\n * Loads system configuration from the cfg file.\n */\n private boolean loadSystemConfiguration() {\n boolean result = true;\n\n saveMRUConfigFiles();\n\n final WaitDialog waitDlg = new WaitDialog(\n \"Loading system configuration, please wait...\");\n\n waitDlg.setAlwaysOnTop(true);\n waitDlg.showDialog();\n this.setEnabled(false);\n\n try {\n if (sysConfigFile_.length() > 0) {\n GUIUtils.preventDisplayAdapterChangeExceptions();\n core_.waitForSystem();\n ignorePropertyChanges_ = true;\n core_.loadSystemConfiguration(sysConfigFile_);\n ignorePropertyChanges_ = false;\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n }\n } catch (final Exception err) {\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n ReportingUtils.showError(err);\n result = false;\n } finally {\n waitDlg.closeDialog();\n }\n setEnabled(true);\n initializeGUI();\n\n updateSwitchConfigurationMenu();\n\n FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));\n\n return result;\n }\n\n private void saveMRUConfigFiles() {\n if (0 < sysConfigFile_.length()) {\n if (MRUConfigFiles_.contains(sysConfigFile_)) {\n MRUConfigFiles_.remove(sysConfigFile_);\n }\n if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {\n MRUConfigFiles_.remove(maxMRUCfgs_ - 1);\n }\n MRUConfigFiles_.add(0, sysConfigFile_);\n // save the MRU list to the preferences\n for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {\n String value = \"\";\n if (null != MRUConfigFiles_.get(icfg)) {\n value = MRUConfigFiles_.get(icfg).toString();\n }\n mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);\n }\n }\n }\n\n private void loadMRUConfigFiles() {\n sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);\n // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,\n // startupScriptFile_);\n MRUConfigFiles_ = new ArrayList();\n for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {\n String value = \"\";\n value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);\n if (0 < value.length()) {\n File ruFile = new File(value);\n if (ruFile.exists()) {\n if (!MRUConfigFiles_.contains(value)) {\n MRUConfigFiles_.add(value);\n }\n }\n }\n }\n // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE\n if (0 < sysConfigFile_.length()) {\n if (!MRUConfigFiles_.contains(sysConfigFile_)) {\n // in case persistant data is inconsistent\n if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {\n MRUConfigFiles_.remove(maxMRUCfgs_ - 1);\n }\n MRUConfigFiles_.add(0, sysConfigFile_);\n }\n }\n }\n\n /**\n * Opens Acquisition dialog.\n */\n private void openAcqControlDialog() {\n try {\n if (acqControlWin_ == null) {\n acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_);\n }\n if (acqControlWin_.isActive()) {\n acqControlWin_.setTopPosition();\n }\n\n acqControlWin_.setVisible(true);\n \n acqControlWin_.repaint();\n\n } catch (Exception exc) {\n ReportingUtils.showError(exc,\n \"\\nAcquistion window failed to open due to invalid or corrupted settings.\\n\"\n + \"Try resetting registry settings to factory defaults (Menu Tools|Options).\");\n }\n }\n \n\n private void updateChannelCombos() {\n if (this.acqControlWin_ != null) {\n this.acqControlWin_.updateChannelAndGroupCombo();\n }\n }\n \n private void runHardwareWizard() {\n try {\n if (configChanged_) {\n Object[] options = {\"Yes\", \"No\"};\n int n = JOptionPane.showOptionDialog(null,\n \"Save Changed Configuration?\", \"Micro-Manager\",\n JOptionPane.YES_NO_OPTION,\n JOptionPane.QUESTION_MESSAGE, null, options,\n options[0]);\n if (n == JOptionPane.YES_OPTION) {\n saveConfigPresets();\n }\n configChanged_ = false;\n }\n\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n\n // unload all devices before starting configurator\n core_.reset();\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n // run Configurator\n ConfiguratorDlg2 cfg2 = null;\n try {\n setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));\n cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);\n } finally {\n setCursor(Cursor.getDefaultCursor()); \t\t \n }\n\n if (cfg2 == null)\n {\n ReportingUtils.showError(\"Failed to launch Hardware Configuration Wizard\");\n return;\n }\n cfg2.setVisible(true);\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n // re-initialize the system with the new configuration file\n sysConfigFile_ = cfg2.getFileName();\n\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n loadSystemConfiguration();\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n if (liveRunning) {\n enableLiveMode(liveRunning);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n private void autofocusNow() {\n if (afMgr_.getDevice() != null) {\n new Thread() {\n\n @Override\n public void run() {\n try {\n boolean lmo = isLiveModeOn();\n if (lmo) {\n enableLiveMode(false);\n }\n afMgr_.getDevice().fullFocus();\n if (lmo) {\n enableLiveMode(true);\n }\n } catch (MMException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }.start(); // or any other method from Autofocus.java API\n }\n }\n \n\n private class ExecuteAcq implements Runnable {\n\n public ExecuteAcq() {\n }\n\n @Override\n public void run() {\n if (acqControlWin_ != null) {\n acqControlWin_.runAcquisition();\n }\n }\n }\n\n private void testForAbortRequests() throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n }\n }\n\n \n \n // //////////////////////////////////////////////////////////////////////////\n // Script interface\n // //////////////////////////////////////////////////////////////////////////\n\n @Override\n public String getVersion() {\n return MMVersion.VERSION_STRING;\n }\n \n /**\n * Inserts version info for various components in the Corelog\n */\n @Override\n public void logStartupProperties() {\n core_.logMessage(\"MM Studio version: \" + getVersion());\n core_.logMessage(core_.getVersionInfo());\n core_.logMessage(core_.getAPIVersionInfo());\n core_.logMessage(\"Operating System: \" + System.getProperty(\"os.name\") +\n \" (\" + System.getProperty(\"os.arch\") + \") \" + System.getProperty(\"os.version\"));\n core_.logMessage(\"JVM: \" + System.getProperty(\"java.vm.name\") +\n \", version \" + System.getProperty(\"java.version\") + \", \" +\n System.getProperty(\"sun.arch.data.model\") + \"-bit\");\n }\n \n @Override\n public void makeActive() {\n toFront();\n }\n \n \n @Override\n public boolean displayImage(TaggedImage ti) {\n normalizeTags(ti);\n return displayTaggedImage(ti, true);\n }\n \n /**\n * Opens a dialog to record stage positions\n */\n @Override\n public void showXYPositionList() {\n checkPosListDlg();\n posListDlg_.setVisible(true);\n }\n\n \n @Override\n public void setConfigChanged(boolean status) {\n configChanged_ = status;\n setConfigSaveButtonStatus(configChanged_);\n }\n \n /**\n * Lets JComponents register themselves so that their background can be\n * manipulated\n */\n @Override\n public void addMMBackgroundListener(Component comp) {\n if (MMFrames_.contains(comp))\n return;\n MMFrames_.add(comp);\n }\n\n /**\n * Lets JComponents remove themselves from the list whose background gets\n * changes\n */\n @Override\n public void removeMMBackgroundListener(Component comp) {\n if (!MMFrames_.contains(comp))\n return;\n MMFrames_.remove(comp);\n }\n\n\n /**\n * Returns exposure time for the desired preset in the given channelgroup\n * Acquires its info from the preferences\n * Same thing is used in MDA window, but this class keeps its own copy\n * \n * @param channelGroup\n * @param channel - \n * @param defaultExp - default value\n * @return exposure time\n */\n @Override\n public double getChannelExposureTime(String channelGroup, String channel,\n double defaultExp) {\n return exposurePrefs_.getDouble(\"Exposure_\" + channelGroup\n + \"_\" + channel, defaultExp);\n }\n\n /**\n * Updates the exposure time in the given preset \n * Will also update current exposure if it the given channel and channelgroup\n * are the current one\n * \n * @param channelGroup - \n * \n * @param channel - preset for which to change exposure time\n * @param exposure - desired exposure time\n */\n @Override\n public void setChannelExposureTime(String channelGroup, String channel,\n double exposure) {\n try {\n exposurePrefs_.putDouble(\"Exposure_\" + channelGroup + \"_\"\n + channel, exposure);\n if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) {\n if (channel != null && !channel.equals(\"\") && \n channel.equals(core_.getCurrentConfigFromCache(channelGroup))) {\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));\n setExposure();\n }\n }\n } catch (Exception ex) {\n ReportingUtils.logError(\"Failed to set Exposure prefs using Channelgroup: \"\n + channelGroup + \", channel: \" + channel + \", exposure: \" + exposure);\n }\n }\n \n @Override\n public void enableRoiButtons(final boolean enabled) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n setRoiButton_.setEnabled(enabled);\n clearRoiButton_.setEnabled(enabled);\n }\n });\n }\n\n @Override\n public boolean getAutoreloadOption() {\n return options_.autoreloadDevices_;\n }\n\n /**\n * Returns the current background color\n * @return current background color\n */\n @Override\n public Color getBackgroundColor() {\n return guiColors_.background.get((options_.displayBackground_));\n }\n\n /*\n * Changes background color of this window and all other MM windows\n */\n @Override\n public void setBackgroundStyle(String backgroundType) {\n setBackground(guiColors_.background.get((backgroundType)));\n paint(MMStudioMainFrame.this.getGraphics());\n \n // sets background of all registered Components\n for (Component comp:MMFrames_) {\n if (comp != null)\n comp.setBackground(guiColors_.background.get(backgroundType));\n }\n }\n\n @Override\n public String getBackgroundStyle() {\n return options_.displayBackground_;\n }\n\n \n @Override\n public ImageWindow getSnapLiveWin() {\n if (simpleDisplay_ == null) {\n return null;\n }\n return simpleDisplay_.getHyperImage().getWindow();\n }\n \n \n /**\n * @Deprecated - used to be in api/AcquisitionEngine\n */\n public void startAcquisition() throws MMScriptException {\n testForAbortRequests();\n SwingUtilities.invokeLater(new ExecuteAcq());\n }\n\n @Override\n public String runAcquisition() throws MMScriptException {\n if (SwingUtilities.isEventDispatchThread()) {\n throw new MMScriptException(\"Acquisition can not be run from this (EDT) thread\");\n }\n testForAbortRequests();\n if (acqControlWin_ != null) {\n String name = acqControlWin_.runAcquisition();\n try {\n while (acqControlWin_.isAcquisitionRunning()) {\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n ReportingUtils.showError(e);\n }\n return name;\n } else {\n throw new MMScriptException(\n \"Acquisition setup window must be open for this command to work.\");\n }\n }\n\n @Override\n public String runAcquisition(String name, String root)\n throws MMScriptException {\n testForAbortRequests();\n if (acqControlWin_ != null) {\n String acqName = acqControlWin_.runAcquisition(name, root);\n try {\n while (acqControlWin_.isAcquisitionRunning()) {\n Thread.sleep(100);\n }\n // ensure that the acquisition has finished.\n // This does not seem to work, needs something better\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n boolean finished = false;\n while (!finished) {\n ImageCache imCache = acq.getImageCache();\n if (imCache != null) {\n if (imCache.isFinished()) {\n finished = true;\n } else {\n Thread.sleep(100);\n }\n }\n }\n\n } catch (InterruptedException e) {\n ReportingUtils.showError(e);\n }\n return acqName;\n } else {\n throw new MMScriptException(\n \"Acquisition setup window must be open for this command to work.\");\n }\n }\n\n /**\n * @Deprecated used to be part of api\n */\n public String runAcqusition(String name, String root) throws MMScriptException {\n return runAcquisition(name, root);\n }\n\n /**\n * Loads acquisition settings from file\n * @param path file containing previously saved acquisition settings\n * @throws MMScriptException \n */\n @Override\n public void loadAcquisition(String path) throws MMScriptException {\n testForAbortRequests();\n try {\n engine_.shutdown();\n\n // load protocol\n if (acqControlWin_ != null) {\n acqControlWin_.loadAcqSettingsFromFile(path);\n }\n } catch (Exception ex) {\n throw new MMScriptException(ex.getMessage());\n }\n\n }\n\n @Override\n public void setPositionList(PositionList pl) throws MMScriptException {\n testForAbortRequests();\n // use serialization to clone the PositionList object\n posList_ = pl; // PositionList.newInstance(pl);\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n if (posListDlg_ != null)\n posListDlg_.setPositionList(posList_);\n \n if (engine_ != null)\n engine_.setPositionList(posList_);\n \n if (acqControlWin_ != null)\n acqControlWin_.updateGUIContents();\n }\n });\n }\n\n @Override\n public PositionList getPositionList() throws MMScriptException {\n testForAbortRequests();\n // use serialization to clone the PositionList object\n return posList_; //PositionList.newInstance(posList_);\n }\n\n @Override\n public void sleep(long ms) throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n scriptPanel_.sleep(ms);\n }\n }\n\n @Override\n public String getUniqueAcquisitionName(String stub) {\n return acqMgr_.getUniqueAcquisitionName(stub);\n }\n \n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,\n nrPositions, true, false);\n }\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices) throws MMScriptException {\n openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);\n }\n \n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions, boolean show)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);\n }\n\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, boolean show)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);\n } \n\n @Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save)\n throws MMScriptException {\n acqMgr_.openAcquisition(name, rootDir, show, save);\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);\n }\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, boolean show, boolean virtual)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);\n }\n\n //@Override\n public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {\n return createAcquisition(summaryMetadata, diskCached, false);\n }\n \n @Override\n @Deprecated\n public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) {\n return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff);\n }\n \n //@Override\n public void initializeSimpleAcquisition(String name, int width, int height,\n int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);\n acq.initializeSimpleAcq();\n }\n \n @Override\n public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n //number of multi-cam cameras is set to 1 here for backwards compatibility\n //might want to change this later\n acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1);\n acq.initialize();\n }\n\n @Override\n public int getAcquisitionImageWidth(String acqName) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getWidth();\n }\n\n @Override\n public int getAcquisitionImageHeight(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getHeight();\n }\n\n @Override\n public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getBitDepth();\n }\n \n @Override\n public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getByteDepth();\n }\n\n @Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getMultiCameraNumChannels();\n }\n \n @Override\n public Boolean acquisitionExists(String name) {\n return acqMgr_.acquisitionExists(name);\n }\n\n @Override\n public void closeAcquisition(String name) throws MMScriptException {\n acqMgr_.closeAcquisition(name);\n }\n\n /**\n * @Deprecated use closeAcquisitionWindow instead\n * @Deprecated - used to be in api/AcquisitionEngine\n */\n public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {\n acqMgr_.closeImageWindow(acquisitionName);\n }\n\n @Override\n public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {\n acqMgr_.closeImageWindow(acquisitionName);\n }\n\n /**\n * @Deprecated - used to be in api/AcquisitionEngine\n * Since Burst and normal acquisition are now carried out by the same engine,\n * loadBurstAcquistion simply calls loadAcquisition\n * t\n * @param path - path to file specifying acquisition settings\n */\n public void loadBurstAcquisition(String path) throws MMScriptException {\n this.loadAcquisition(path);\n }\n\n @Override\n public void refreshGUI() {\n updateGUI(true);\n }\n \n @Override\n public void refreshGUIFromCache() {\n updateGUI(true, true);\n }\n\n @Override\n public void setAcquisitionProperty(String acqName, String propertyName,\n String value) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n acq.setProperty(propertyName, value);\n }\n\n public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {\n// acqMgr_.getAcquisition(acqName).setSystemState(md);\n setAcquisitionSummary(acqName, md);\n }\n\n //@Override\n public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {\n acqMgr_.getAcquisition(acqName).setSummaryProperties(md);\n }\n\n @Override\n public void setImageProperty(String acqName, int frame, int channel,\n int slice, String propName, String value) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n acq.setProperty(frame, channel, slice, propName, value);\n }\n\n\n @Override\n public String getCurrentAlbum() {\n return acqMgr_.getCurrentAlbum();\n }\n \n @Override\n public void enableLiveMode(boolean enable) {\n if (core_ == null) {\n return;\n }\n if (enable == isLiveModeOn()) {\n return;\n }\n if (enable) {\n try {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n updateButtonsForLiveMode(false);\n return;\n }\n if (liveModeTimer_ == null) {\n liveModeTimer_ = new LiveModeTimer();\n }\n liveModeTimer_.begin();\n callLiveModeListeners(enable);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n liveModeTimer_.stop();\n callLiveModeListeners(false);\n updateButtonsForLiveMode(false);\n return;\n }\n } else {\n liveModeTimer_.stop();\n callLiveModeListeners(enable);\n }\n updateButtonsForLiveMode(enable);\n }\n\n public String createNewAlbum() {\n return acqMgr_.createNewAlbum();\n }\n\n public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n int f = 1 + acq.getLastAcquiredFrame();\n try {\n MDUtils.setFrameIndex(taggedImg.tags, f);\n } catch (JSONException e) {\n throw new MMScriptException(\"Unable to set the frame index.\");\n }\n acq.insertTaggedImage(taggedImg, f, 0, 0);\n }\n\n @Override\n public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {\n addToAlbum(taggedImg, null);\n }\n \n public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {\n normalizeTags(taggedImg);\n acqMgr_.addToAlbum(taggedImg,displaySettings);\n }\n\n public void addImage(String name, Object img, int frame, int channel,\n int slice) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.insertImage(img, frame, channel, slice);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n if (!acq.isInitialized()) {\n JSONObject tags = taggedImg.tags;\n \n // initialize physical dimensions of the image\n try {\n int width = tags.getInt(MMTags.Image.WIDTH);\n int height = tags.getInt(MMTags.Image.HEIGHT);\n int byteDepth = MDUtils.getDepth(tags);\n int bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);\n initializeAcquisition(name, width, height, byteDepth, bitDepth);\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n }\n acq.insertImage(taggedImg);\n }\n \n @Override\n /**\n * The basic method for adding images to an existing data set.\n * If the acquisition was not previously initialized, it will attempt to initialize it from the available image data\n */\n public void addImageToAcquisition(String name,\n int frame,\n int channel,\n int slice,\n int position,\n TaggedImage taggedImg) throws MMScriptException {\n\n // TODO: complete the tag set and initialize the acquisition\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n\n int positions = acq.getPositions();\n \n // check position, for multi-position data set the number of declared positions should be at least 2\n if (acq.getPositions() <= 1 && position > 0) {\n throw new MMScriptException(\"The acquisition was open as a single position data set.\\n\"\n + \"Open acqusition with two or more positions in order to crate a multi-position data set.\");\n }\n\n // check position, for multi-position data set the number of declared positions should be at least 2\n if (acq.getChannels() <= channel) {\n throw new MMScriptException(\"This acquisition was opened with \" + acq.getChannels() + \" channels.\\n\"\n + \"The channel number must not exceed declared number of positions.\");\n }\n\n\n JSONObject tags = taggedImg.tags;\n\n // if the acquisition was not previously initialized, set physical dimensions of the image\n if (!acq.isInitialized()) {\n\n // automatically initialize physical dimensions of the image\n try {\n int width = tags.getInt(MMTags.Image.WIDTH);\n int height = tags.getInt(MMTags.Image.HEIGHT);\n int byteDepth = MDUtils.getDepth(tags);\n int bitDepth = byteDepth * 8;\n if (tags.has(MMTags.Image.BIT_DEPTH)) {\n bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);\n }\n initializeAcquisition(name, width, height, byteDepth, bitDepth);\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n }\n\n // create required coordinate tags\n try {\n tags.put(MMTags.Image.FRAME_INDEX, frame);\n tags.put(MMTags.Image.FRAME, frame);\n tags.put(MMTags.Image.CHANNEL_INDEX, channel);\n tags.put(MMTags.Image.SLICE_INDEX, slice);\n tags.put(MMTags.Image.POS_INDEX, position);\n\n if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {\n // add default setting\n tags.put(MMTags.Summary.SLICES_FIRST, true);\n tags.put(MMTags.Summary.TIME_FIRST, false);\n }\n\n if (acq.getPositions() > 1) {\n // if no position name is defined we need to insert a default one\n if (tags.has(MMTags.Image.POS_NAME)) {\n tags.put(MMTags.Image.POS_NAME, \"Pos\" + position);\n }\n }\n\n // update frames if necessary\n if (acq.getFrames() <= frame) {\n acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));\n }\n\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n\n // System.out.println(\"Inserting frame: \" + frame + \", channel: \" + channel + \", slice: \" + slice + \", pos: \" + position);\n acq.insertImage(taggedImg);\n }\n\n @Override\n /**\n * A quick way to implicitly snap an image and add it to the data set. Works\n * in the same way as above.\n */\n public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException {\n TaggedImage ti;\n try {\n if (core_.isSequenceRunning()) {\n ti = core_.getLastTaggedImage();\n } else {\n core_.snapImage();\n ti = core_.getTaggedImage();\n }\n MDUtils.setChannelIndex(ti.tags, channel);\n MDUtils.setFrameIndex(ti.tags, frame);\n MDUtils.setSliceIndex(ti.tags, slice);\n\n MDUtils.setPositionIndex(ti.tags, position);\n\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n if (!acq.isInitialized()) {\n long width = core_.getImageWidth();\n long height = core_.getImageHeight();\n long depth = core_.getBytesPerPixel();\n long bitDepth = core_.getImageBitDepth();\n int multiCamNumCh = (int) core_.getNumberOfCameraChannels();\n\n acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh);\n acq.initialize();\n }\n\n if (acq.getPositions() > 1) {\n MDUtils.setPositionName(ti.tags, \"Pos\" + position);\n }\n\n addImageToAcquisition(name, frame, channel, slice, position, ti);\n } catch (Exception e) {\n throw new MMScriptException(e);\n }\n }\n\n //@Override\n public void addImage(String name, TaggedImage img, boolean updateDisplay) throws MMScriptException {\n acqMgr_.getAcquisition(name).insertImage(img, updateDisplay);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg,\n boolean updateDisplay,\n boolean waitForDisplay) throws MMScriptException {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel,\n int slice, int position) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel, \n int slice, int position, boolean updateDisplay) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n } \n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel,\n int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n /**\n * Closes all acquisitions\n */\n @Override\n public void closeAllAcquisitions() {\n acqMgr_.closeAll();\n }\n\n @Override\n public String[] getAcquisitionNames()\n {\n return acqMgr_.getAcqusitionNames();\n }\n \n @Override\n @Deprecated\n public MMAcquisition getAcquisition(String name) throws MMScriptException {\n return acqMgr_.getAcquisition(name);\n }\n \n @Override\n public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException {\n return getAcquisition(acquisitionName).getImageCache();\n }\n\n private class ScriptConsoleMessage implements Runnable {\n\n String msg_;\n\n public ScriptConsoleMessage(String text) {\n msg_ = text;\n }\n\n @Override\n public void run() {\n if (scriptPanel_ != null)\n scriptPanel_.message(msg_);\n }\n }\n\n @Override\n public void message(String text) throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n\n SwingUtilities.invokeLater(new ScriptConsoleMessage(text));\n }\n }\n\n @Override\n public void clearMessageWindow() throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n scriptPanel_.clearOutput();\n }\n }\n\n public void clearOutput() throws MMScriptException {\n clearMessageWindow();\n }\n\n public void clear() throws MMScriptException {\n clearMessageWindow();\n }\n\n @Override\n public void setChannelContrast(String title, int channel, int min, int max)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelContrast(channel, min, max);\n }\n\n @Override\n public void setChannelName(String title, int channel, String name)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelName(channel, name);\n\n }\n\n @Override\n public void setChannelColor(String title, int channel, Color color)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelColor(channel, color.getRGB());\n }\n \n @Override\n public void setContrastBasedOnFrame(String title, int frame, int slice)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setContrastBasedOnFrame(frame, slice);\n }\n\n @Override\n public void setStagePosition(double z) throws MMScriptException {\n try {\n core_.setPosition(core_.getFocusDevice(),z);\n core_.waitForDevice(core_.getFocusDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public void setRelativeStagePosition(double z) throws MMScriptException {\n try {\n core_.setRelativePosition(core_.getFocusDevice(), z);\n core_.waitForDevice(core_.getFocusDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n\n @Override\n public void setXYStagePosition(double x, double y) throws MMScriptException {\n try {\n core_.setXYPosition(core_.getXYStageDevice(), x, y);\n core_.waitForDevice(core_.getXYStageDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {\n try {\n core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);\n core_.waitForDevice(core_.getXYStageDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public Point2D.Double getXYStagePosition() throws MMScriptException {\n String stage = core_.getXYStageDevice();\n if (stage.length() == 0) {\n throw new MMScriptException(\"XY Stage device is not available\");\n }\n\n double x[] = new double[1];\n double y[] = new double[1];\n try {\n core_.getXYPosition(stage, x, y);\n Point2D.Double pt = new Point2D.Double(x[0], y[0]);\n return pt;\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public String getXYStageName() {\n return core_.getXYStageDevice();\n }\n\n @Override\n public void setXYOrigin(double x, double y) throws MMScriptException {\n String xyStage = core_.getXYStageDevice();\n try {\n core_.setAdapterOriginXY(xyStage, x, y);\n } catch (Exception e) {\n throw new MMScriptException(e);\n }\n }\n\n public AcquisitionWrapperEngine getAcquisitionEngine() {\n return engine_;\n }\n\n @Override\n public String installAutofocusPlugin(String className) {\n try {\n return installAutofocusPlugin(Class.forName(className));\n } catch (ClassNotFoundException e) {\n String msg = \"Internal error: AF manager not instantiated.\";\n ReportingUtils.logError(e, msg);\n return msg;\n }\n }\n\n public String installAutofocusPlugin(Class> autofocus) {\n String msg = autofocus.getSimpleName() + \" module loaded.\";\n if (afMgr_ != null) {\n afMgr_.setAFPluginClassName(autofocus.getSimpleName());\n try {\n afMgr_.refresh();\n } catch (MMException e) {\n msg = e.getMessage();\n ReportingUtils.logError(e);\n }\n } else {\n msg = \"Internal error: AF manager not instantiated.\";\n }\n return msg;\n }\n\n public CMMCore getCore() {\n return core_;\n }\n\n @Override\n public IAcquisitionEngine2010 getAcquisitionEngine2010() {\n try {\n acquisitionEngine2010LoadingThread_.join();\n if (acquisitionEngine2010_ == null) {\n acquisitionEngine2010_ = (IAcquisitionEngine2010) acquisitionEngine2010Class_.getConstructor(ScriptInterface.class).newInstance(this);\n }\n return acquisitionEngine2010_;\n } catch (Exception e) {\n ReportingUtils.logError(e);\n return null;\n }\n }\n \n @Override\n public void addImageProcessor(DataProcessor processor) {\n getAcquisitionEngine().addImageProcessor(processor);\n }\n\n @Override\n public void removeImageProcessor(DataProcessor processor) {\n getAcquisitionEngine().removeImageProcessor(processor);\n }\n\n @Override\n public ArrayList> getImageProcessorPipeline() {\n return getAcquisitionEngine().getImageProcessorPipeline();\n }\n\n public void registerProcessorClass(Class> processorClass, String name) {\n getAcquisitionEngine().registerProcessorClass(processorClass, name);\n }\n\n // NB will need @Override tags once these functions are exposed in the \n // ScriptInterface.\n @Override\n public void setImageProcessorPipeline(List> pipeline) {\n getAcquisitionEngine().setImageProcessorPipeline(pipeline);\n }\n\n @Override\n public void setPause(boolean state) {\n\t getAcquisitionEngine().setPause(state);\n }\n\n @Override\n public boolean isPaused() {\n\t return getAcquisitionEngine().isPaused();\n }\n \n @Override\n public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) {\n\t getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable);\n }\n\n @Override\n public void clearRunnables() {\n\t getAcquisitionEngine().clearRunnables();\n }\n \n @Override\n public SequenceSettings getAcquisitionSettings() {\n\t if (engine_ == null)\n\t\t return new SequenceSettings();\n\t return engine_.getSequenceSettings();\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public SequenceSettings getAcqusitionSettings() {\n return getAcquisitionSettings();\n }\n \n @Override\n public void setAcquisitionSettings(SequenceSettings ss) {\n if (engine_ == null)\n return;\n \n engine_.setSequenceSettings(ss);\n acqControlWin_.updateGUIContents();\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public void setAcqusitionSettings(SequenceSettings ss) {\n setAcquisitionSettings(ss);\n }\n \n @Override\n public String getAcquisitionPath() {\n\t if (engine_ == null)\n\t\t return null;\n\t return engine_.getImageCache().getDiskLocation();\n }\n \n @Override\n public void promptToSaveAcquisition(String name, boolean prompt) throws MMScriptException {\n getAcquisition(name).promptToSave(prompt);\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException {\n promptToSaveAcquisition(name, prompt);\n }\n\n @Override\n public void setROI(Rectangle r) throws MMScriptException {\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n try {\n core_.setROI(r.x, r.y, r.width, r.height);\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n updateStaticInfo();\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n }\n\n public void snapAndAddToImage5D() {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n try {\n if (this.isLiveModeOn()) {\n copyFromLiveModeToAlbum(simpleDisplay_);\n } else {\n doSnap(true);\n }\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n }\n }\n\n public void setAcquisitionEngine(AcquisitionWrapperEngine eng) {\n engine_ = eng;\n }\n \n public void suspendLiveMode() {\n liveModeSuspended_ = isLiveModeOn();\n enableLiveMode(false);\n }\n\n public void resumeLiveMode() {\n if (liveModeSuspended_) {\n enableLiveMode(true);\n }\n }\n\n @Override\n public Autofocus getAutofocus() {\n return afMgr_.getDevice();\n }\n\n @Override\n public void showAutofocusDialog() {\n if (afMgr_.getDevice() != null) {\n afMgr_.showOptionsDialog();\n }\n }\n\n @Override\n public AutofocusManager getAutofocusManager() {\n return afMgr_;\n }\n\n public void selectConfigGroup(String groupName) {\n configPad_.setGroup(groupName);\n }\n\n public String regenerateDeviceList() {\n Cursor oldc = Cursor.getDefaultCursor();\n Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);\n setCursor(waitc);\n StringBuffer resultFile = new StringBuffer();\n MicroscopeModel.generateDeviceListFile(resultFile, core_);\n //MicroscopeModel.generateDeviceListFile();\n setCursor(oldc);\n return resultFile.toString();\n }\n \n @Override\n public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException {\n if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) || \n imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) {\n throw new MMScriptException(\"Unrecognized saving class\");\n }\n ImageUtils.setImageStorageClass(imageSavingClass);\n if (acqControlWin_ != null) {\n acqControlWin_.updateSavingTypeButtons();\n }\n }\n \n \n /**\n * Allows MMListeners to register themselves\n */\n @Override\n public void addMMListener(MMListenerInterface newL) {\n if (MMListeners_.contains(newL))\n return;\n MMListeners_.add(newL);\n }\n\n /**\n * Allows MMListeners to remove themselves\n */\n @Override\n public void removeMMListener(MMListenerInterface oldL) {\n if (!MMListeners_.contains(oldL))\n return;\n MMListeners_.remove(oldL);\n }\n\n @Override\n public void logMessage(String msg) {\n ReportingUtils.logMessage(msg);\n }\n\n @Override\n public void showMessage(String msg) {\n ReportingUtils.showMessage(msg);\n }\n\n @Override\n public void logError(Exception e, String msg) {\n ReportingUtils.logError(e, msg);\n }\n\n @Override\n public void logError(Exception e) {\n ReportingUtils.logError(e);\n }\n\n @Override\n public void logError(String msg) {\n ReportingUtils.logError(msg);\n }\n\n @Override\n public void showError(Exception e, String msg) {\n ReportingUtils.showError(e, msg);\n }\n\n @Override\n public void showError(Exception e) {\n ReportingUtils.showError(e);\n }\n\n @Override\n public void showError(String msg) {\n ReportingUtils.showError(msg);\n }\n \n}\n"},"new_file":{"kind":"string","value":"mmstudio/src/org/micromanager/MMStudioMainFrame.java"},"old_contents":{"kind":"string","value":"///////////////////////////////////////////////////////////////////////////////\n//FILE: MMStudioMainFrame.java\n//PROJECT: Micro-Manager\n//SUBSYSTEM: mmstudio\n//-----------------------------------------------------------------------------\n//AUTHOR: Nenad Amodaj, nenad@amodaj.com, Jul 18, 2005\n// Modifications by Arthur Edelstein, Nico Stuurman, Henry Pinkard\n//COPYRIGHT: University of California, San Francisco, 2006-2013\n// 100X Imaging Inc, www.100ximaging.com, 2008\n//LICENSE: This file is distributed under the BSD license.\n// License text is included with the source distribution.\n// This file is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty\n// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n// IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n//CVS: $Id$\n//\npackage org.micromanager;\n\nimport ij.IJ;\nimport ij.ImageJ;\nimport ij.ImagePlus;\nimport ij.WindowManager;\nimport ij.gui.Line;\nimport ij.gui.Roi;\nimport ij.process.ImageProcessor;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.Rectangle;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.FocusAdapter;\nimport java.awt.event.FocusEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.awt.geom.Point2D;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\nimport javax.swing.AbstractButton;\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JCheckBoxMenuItem;\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JSplitPane;\nimport javax.swing.JTextField;\nimport javax.swing.JToggleButton;\nimport javax.swing.SpringLayout;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\nimport javax.swing.ToolTipManager;\nimport javax.swing.UIManager;\n\nimport mmcorej.CMMCore;\nimport mmcorej.DeviceType;\nimport mmcorej.MMCoreJ;\nimport mmcorej.MMEventCallback;\nimport mmcorej.StrVector;\n\nimport org.json.JSONObject;\nimport org.micromanager.acquisition.AcquisitionManager;\nimport org.micromanager.api.Autofocus;\nimport org.micromanager.api.DataProcessor;\nimport org.micromanager.api.MMPlugin;\nimport org.micromanager.api.MMProcessorPlugin;\nimport org.micromanager.api.MMTags;\nimport org.micromanager.api.PositionList;\nimport org.micromanager.api.ScriptInterface;\nimport org.micromanager.api.MMListenerInterface;\nimport org.micromanager.api.SequenceSettings;\nimport org.micromanager.conf2.ConfiguratorDlg2;\nimport org.micromanager.conf2.MMConfigFileException;\nimport org.micromanager.conf2.MicroscopeModel;\nimport org.micromanager.events.EventManager;\nimport org.micromanager.graph.GraphData;\nimport org.micromanager.graph.GraphFrame;\nimport org.micromanager.navigation.CenterAndDragListener;\nimport org.micromanager.navigation.XYZKeyListener;\nimport org.micromanager.navigation.ZWheelListener;\nimport org.micromanager.pipelineUI.PipelinePanel;\nimport org.micromanager.utils.AutofocusManager;\nimport org.micromanager.utils.ContrastSettings;\nimport org.micromanager.utils.GUIColors;\nimport org.micromanager.utils.GUIUtils;\nimport org.micromanager.utils.JavaUtils;\nimport org.micromanager.utils.MMException;\nimport org.micromanager.utils.MMScriptException;\nimport org.micromanager.utils.NumberUtils;\nimport org.micromanager.utils.TextUtils;\nimport org.micromanager.utils.WaitDialog;\n\nimport bsh.EvalError;\nimport bsh.Interpreter;\n\nimport com.swtdesigner.SwingResourceManager;\n\nimport ij.gui.ImageCanvas;\nimport ij.gui.ImageWindow;\nimport ij.gui.Toolbar;\n\nimport java.awt.*;\nimport java.awt.dnd.DropTarget;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport mmcorej.TaggedImage;\n\nimport org.json.JSONException;\nimport org.micromanager.acquisition.*;\nimport org.micromanager.api.ImageCache;\nimport org.micromanager.api.IAcquisitionEngine2010;\nimport org.micromanager.graph.HistogramSettings;\nimport org.micromanager.internalinterfaces.LiveModeListener;\nimport org.micromanager.utils.DragDropUtil;\nimport org.micromanager.utils.FileDialogs;\nimport org.micromanager.utils.FileDialogs.FileType;\nimport org.micromanager.utils.HotKeysDialog;\nimport org.micromanager.utils.ImageUtils;\nimport org.micromanager.utils.MDUtils;\nimport org.micromanager.utils.MMKeyDispatcher;\nimport org.micromanager.utils.ReportingUtils;\nimport org.micromanager.utils.UIMonitor;\n\n\n\n\n\n/*\n * Main panel and application class for the MMStudio.\n */\npublic class MMStudioMainFrame extends JFrame implements ScriptInterface {\n\n private static final String MICRO_MANAGER_TITLE = \"Micro-Manager\";\n private static final long serialVersionUID = 3556500289598574541L;\n private static final String MAIN_FRAME_X = \"x\";\n private static final String MAIN_FRAME_Y = \"y\";\n private static final String MAIN_FRAME_WIDTH = \"width\";\n private static final String MAIN_FRAME_HEIGHT = \"height\";\n private static final String MAIN_FRAME_DIVIDER_POS = \"divider_pos\";\n private static final String MAIN_EXPOSURE = \"exposure\";\n private static final String MAIN_SAVE_METHOD = \"saveMethod\";\n private static final String SYSTEM_CONFIG_FILE = \"sysconfig_file\";\n private static final String OPEN_ACQ_DIR = \"openDataDir\";\n private static final String SCRIPT_CORE_OBJECT = \"mmc\";\n private static final String SCRIPT_ACQENG_OBJECT = \"acq\";\n private static final String SCRIPT_GUI_OBJECT = \"gui\";\n private static final String AUTOFOCUS_DEVICE = \"autofocus_device\";\n private static final String MOUSE_MOVES_STAGE = \"mouse_moves_stage\";\n private static final String EXPOSURE_SETTINGS_NODE = \"MainExposureSettings\";\n private static final String CONTRAST_SETTINGS_NODE = \"MainContrastSettings\";\n private static final int TOOLTIP_DISPLAY_DURATION_MILLISECONDS = 15000;\n private static final int TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS = 2000;\n\n\n // cfg file saving\n private static final String CFGFILE_ENTRY_BASE = \"CFGFileEntry\"; // + {0, 1, 2, 3, 4}\n // GUI components\n private JComboBox comboBinning_;\n private JComboBox shutterComboBox_;\n private JTextField textFieldExp_;\n private JLabel labelImageDimensions_;\n private JToggleButton liveButton_;\n private JCheckBox autoShutterCheckBox_;\n private MMOptions options_;\n private boolean runsAsPlugin_;\n private JCheckBoxMenuItem centerAndDragMenuItem_;\n private JButton snapButton_;\n private JButton autofocusNowButton_;\n private JButton autofocusConfigureButton_;\n private JToggleButton toggleShutterButton_;\n private GUIColors guiColors_;\n private GraphFrame profileWin_;\n private PropertyEditor propertyBrowser_;\n private CalibrationListDlg calibrationListDlg_;\n private AcqControlDlg acqControlWin_;\n\n private JMenu pluginMenu_;\n private Map pluginSubMenus_;\n private List MMListeners_\n = Collections.synchronizedList(new ArrayList());\n private List liveModeListeners_\n = Collections.synchronizedList(new ArrayList());\n private List MMFrames_\n = Collections.synchronizedList(new ArrayList());\n private AutofocusManager afMgr_;\n private final static String DEFAULT_CONFIG_FILE_NAME = \"MMConfig_demo.cfg\";\n private final static String DEFAULT_CONFIG_FILE_PROPERTY = \"org.micromanager.default.config.file\";\n private ArrayList MRUConfigFiles_;\n private static final int maxMRUCfgs_ = 5;\n private String sysConfigFile_;\n private String startupScriptFile_;\n private ConfigGroupPad configPad_;\n private LiveModeTimer liveModeTimer_;\n private GraphData lineProfileData_;\n // labels for standard devices\n private String cameraLabel_;\n private String zStageLabel_;\n private String shutterLabel_;\n private String xyStageLabel_;\n // applications settings\n private Preferences mainPrefs_;\n private Preferences systemPrefs_;\n private Preferences colorPrefs_;\n private Preferences exposurePrefs_;\n private Preferences contrastPrefs_;\n\n // MMcore\n private CMMCore core_;\n private AcquisitionWrapperEngine engine_;\n private PositionList posList_;\n private PositionListDlg posListDlg_;\n private String openAcqDirectory_ = \"\";\n private boolean running_;\n private boolean configChanged_ = false;\n private StrVector shutters_ = null;\n\n private JButton saveConfigButton_;\n private ScriptPanel scriptPanel_;\n private PipelinePanel pipelinePanel_;\n private org.micromanager.utils.HotKeys hotKeys_;\n private CenterAndDragListener centerAndDragListener_;\n private ZWheelListener zWheelListener_;\n private XYZKeyListener xyzKeyListener_;\n private AcquisitionManager acqMgr_;\n private static VirtualAcquisitionDisplay simpleDisplay_;\n private Color[] multiCameraColors_ = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN};\n private boolean liveModeSuspended_;\n public Font defaultScriptFont_ = null;\n public static final String SIMPLE_ACQ = \"Snap/Live Window\";\n public static FileType MM_CONFIG_FILE\n = new FileType(\"MM_CONFIG_FILE\",\n \"Micro-Manager Config File\",\n \"./MyScope.cfg\",\n true, \"cfg\");\n\n // Our instance\n private static MMStudioMainFrame gui_;\n // Callback\n private CoreEventCallback cb_;\n // Lock invoked while shutting down\n private final Object shutdownLock_ = new Object();\n\n private JMenuBar menuBar_;\n private ConfigPadButtonPanel configPadButtonPanel_;\n private final JMenu switchConfigurationMenu_;\n private final MetadataPanel metadataPanel_;\n public static FileType MM_DATA_SET \n = new FileType(\"MM_DATA_SET\",\n \"Micro-Manager Image Location\",\n System.getProperty(\"user.home\") + \"/Untitled\",\n false, (String[]) null);\n private Thread acquisitionEngine2010LoadingThread_ = null;\n private Class> acquisitionEngine2010Class_ = null;\n private IAcquisitionEngine2010 acquisitionEngine2010_ = null;\n private final JSplitPane splitPane_;\n private volatile boolean ignorePropertyChanges_; \n private PluginLoader pluginLoader_;\n\n private AbstractButton setRoiButton_;\n private AbstractButton clearRoiButton_;\n\n /**\n * Simple class used to cache static info\n */\n private class StaticInfo {\n\n public long width_;\n public long height_;\n public long bytesPerPixel_;\n public long imageBitDepth_;\n public double pixSizeUm_;\n public double zPos_;\n public double x_;\n public double y_;\n }\n private StaticInfo staticInfo_ = new StaticInfo();\n \n \n /**\n * Main procedure for stand alone operation.\n */\n public static void main(String args[]) {\n try {\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n MMStudioMainFrame frame = new MMStudioMainFrame(false);\n frame.setVisible(true);\n frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n } catch (Throwable e) {\n ReportingUtils.showError(e, \"A java error has caused Micro-Manager to exit.\");\n System.exit(1);\n }\n }\n\n /**\n * MMStudioMainframe constructor\n * @param pluginStatus \n */\n @SuppressWarnings(\"LeakingThisInConstructor\")\n public MMStudioMainFrame(boolean pluginStatus) {\n org.micromanager.diagnostics.ThreadExceptionLogger.setUp();\n\n // Set up event handling early, so following code can subscribe/publish\n // events as needed.\n EventManager manager = new EventManager();\n\n startLoadingPipelineClass();\n\n options_ = new MMOptions();\n try {\n options_.loadSettings();\n } catch (NullPointerException ex) {\n ReportingUtils.logError(ex);\n }\n\n UIMonitor.enable(options_.debugLogEnabled_);\n \n guiColors_ = new GUIColors();\n\n pluginLoader_ = new PluginLoader();\n // plugins_ = new ArrayList();\n\n gui_ = this;\n\n runsAsPlugin_ = pluginStatus;\n setIconImage(SwingResourceManager.getImage(MMStudioMainFrame.class,\n \"icons/microscope.gif\"));\n running_ = true;\n\n acqMgr_ = new AcquisitionManager();\n \n sysConfigFile_ = new File(DEFAULT_CONFIG_FILE_NAME).getAbsolutePath();\n sysConfigFile_ = System.getProperty(DEFAULT_CONFIG_FILE_PROPERTY,\n sysConfigFile_);\n\n if (options_.startupScript_.length() > 0) {\n startupScriptFile_ = new File(options_.startupScript_).getAbsolutePath();\n } else {\n startupScriptFile_ = \"\";\n }\n\n ReportingUtils.SetContainingFrame(gui_);\n \n \n // set the location for app preferences\n try {\n mainPrefs_ = Preferences.userNodeForPackage(this.getClass());\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n systemPrefs_ = mainPrefs_;\n \n colorPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" + \n AcqControlDlg.COLOR_SETTINGS_NODE);\n exposurePrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" + \n EXPOSURE_SETTINGS_NODE);\n contrastPrefs_ = mainPrefs_.node(mainPrefs_.absolutePath() + \"/\" +\n CONTRAST_SETTINGS_NODE);\n \n // check system preferences\n try {\n Preferences p = Preferences.systemNodeForPackage(this.getClass());\n if (null != p) {\n // if we can not write to the systemPrefs, use AppPrefs instead\n if (JavaUtils.backingStoreAvailable(p)) {\n systemPrefs_ = p;\n }\n }\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n \n showRegistrationDialogMaybe();\n\n // load application preferences\n // NOTE: only window size and position preferences are loaded,\n // not the settings for the camera and live imaging -\n // attempting to set those automatically on startup may cause problems\n // with the hardware\n int x = mainPrefs_.getInt(MAIN_FRAME_X, 100);\n int y = mainPrefs_.getInt(MAIN_FRAME_Y, 100);\n int width = mainPrefs_.getInt(MAIN_FRAME_WIDTH, 644);\n int height = mainPrefs_.getInt(MAIN_FRAME_HEIGHT, 570);\n openAcqDirectory_ = mainPrefs_.get(OPEN_ACQ_DIR, \"\");\n try {\n ImageUtils.setImageStorageClass(Class.forName (mainPrefs_.get(MAIN_SAVE_METHOD,\n ImageUtils.getImageStorageClass().getName()) ) );\n } catch (ClassNotFoundException ex) {\n ReportingUtils.logError(ex, \"Class not found error. Should never happen\");\n }\n\n ToolTipManager ttManager = ToolTipManager.sharedInstance();\n ttManager.setDismissDelay(TOOLTIP_DISPLAY_DURATION_MILLISECONDS);\n ttManager.setInitialDelay(TOOLTIP_DISPLAY_INITIAL_DELAY_MILLISECONDS);\n \n setBounds(x, y, width, height);\n setExitStrategy(options_.closeOnExit_);\n setTitle(MICRO_MANAGER_TITLE + \" \" + MMVersion.VERSION_STRING);\n setBackground(guiColors_.background.get((options_.displayBackground_)));\n setMinimumSize(new Dimension(605,480));\n \n menuBar_ = new JMenuBar();\n switchConfigurationMenu_ = new JMenu();\n\n setJMenuBar(menuBar_);\n\n initializeFileMenu();\n initializeToolsMenu();\n\n splitPane_ = createSplitPane(mainPrefs_.getInt(MAIN_FRAME_DIVIDER_POS, 200));\n getContentPane().add(splitPane_);\n\n createTopPanelWidgets((JPanel) splitPane_.getComponent(0));\n \n metadataPanel_ = createMetadataPanel((JPanel) splitPane_.getComponent(1));\n \n setupWindowHandlers();\n \n // Add our own keyboard manager that handles Micro-Manager shortcuts\n MMKeyDispatcher mmKD = new MMKeyDispatcher(gui_);\n KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(mmKD);\n DropTarget dropTarget = new DropTarget(this, new DragDropUtil());\n\n }\n \n private void setupWindowHandlers() {\n // add window listeners\n addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n closeSequence(false);\n }\n\n @Override\n public void windowOpened(WindowEvent e) {\n // -------------------\n // initialize hardware\n // -------------------\n try {\n core_ = new CMMCore();\n } catch(UnsatisfiedLinkError ex) {\n ReportingUtils.showError(ex, \"Failed to load the MMCoreJ_wrap native library\");\n return;\n }\n\n ReportingUtils.setCore(core_);\n core_.enableDebugLog(options_.debugLogEnabled_);\n logStartupProperties();\n \n cameraLabel_ = \"\";\n shutterLabel_ = \"\";\n zStageLabel_ = \"\";\n xyStageLabel_ = \"\";\n engine_ = new AcquisitionWrapperEngine(acqMgr_);\n // processorStackManager_ = new ProcessorStackManager(engine_);\n\n // register callback for MMCore notifications, this is a global\n // to avoid garbage collection\n cb_ = new CoreEventCallback();\n core_.registerCallback(cb_);\n\n try {\n core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);\n } catch (Exception e2) {\n ReportingUtils.showError(e2);\n }\n\n MMStudioMainFrame parent = (MMStudioMainFrame) e.getWindow();\n if (parent != null) {\n engine_.setParentGUI(parent);\n }\n\n loadMRUConfigFiles();\n afMgr_ = new AutofocusManager(gui_);\n Thread pluginInitializer = initializePlugins();\n\n toFront();\n \n if (!options_.doNotAskForConfigFile_) {\n MMIntroDlg introDlg = new MMIntroDlg(MMVersion.VERSION_STRING, MRUConfigFiles_);\n introDlg.setConfigFile(sysConfigFile_);\n introDlg.setBackground(guiColors_.background.get((options_.displayBackground_)));\n introDlg.setVisible(true);\n if (!introDlg.okChosen()) {\n closeSequence(false);\n return;\n }\n sysConfigFile_ = introDlg.getConfigFile();\n }\n saveMRUConfigFiles();\n\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n\n paint(MMStudioMainFrame.this.getGraphics());\n\n engine_.setCore(core_, afMgr_);\n posList_ = new PositionList();\n engine_.setPositionList(posList_);\n // load (but do no show) the scriptPanel\n createScriptPanel();\n // Ditto with the image pipeline panel.\n createPipelinePanel();\n\n // Create an instance of HotKeys so that they can be read in from prefs\n hotKeys_ = new org.micromanager.utils.HotKeys();\n hotKeys_.loadSettings();\n \n // before loading the system configuration, we need to wait \n // until the plugins are loaded\n try { \n pluginInitializer.join(2000);\n } catch (InterruptedException ex) {\n ReportingUtils.logError(ex, \"Plugin loader thread was interupted\");\n }\n \n // if an error occurred during config loading, \n // do not display more errors than needed\n if (!loadSystemConfiguration())\n ReportingUtils.showErrorOn(false);\n\n executeStartupScript();\n\n\n // Create Multi-D window here but do not show it.\n // This window needs to be created in order to properly set the \"ChannelGroup\"\n // based on the Multi-D parameters\n acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, MMStudioMainFrame.this, options_);\n addMMBackgroundListener(acqControlWin_);\n\n configPad_.setCore(core_);\n if (parent != null) {\n configPad_.setParentGUI(parent);\n }\n\n configPadButtonPanel_.setCore(core_);\n\n // initialize controls\n initializeHelpMenu();\n \n String afDevice = mainPrefs_.get(AUTOFOCUS_DEVICE, \"\");\n if (afMgr_.hasDevice(afDevice)) {\n try {\n afMgr_.selectDevice(afDevice);\n } catch (MMException e1) {\n // this error should never happen\n ReportingUtils.showError(e1);\n }\n }\n\n centerAndDragListener_ = new CenterAndDragListener(gui_);\n zWheelListener_ = new ZWheelListener(core_, gui_);\n gui_.addLiveModeListener(zWheelListener_);\n xyzKeyListener_ = new XYZKeyListener(core_, gui_);\n gui_.addLiveModeListener(xyzKeyListener_);\n\n // switch error reporting back on\n ReportingUtils.showErrorOn(true);\n }\n\n private Thread initializePlugins() {\n pluginMenu_ = GUIUtils.createMenuInMenuBar(menuBar_, \"Plugins\");\n Thread myThread = new ThreadPluginLoading(\"Plugin loading\");\n myThread.start();\n return myThread;\n }\n\n class ThreadPluginLoading extends Thread {\n\n public ThreadPluginLoading(String string) {\n super(string);\n }\n\n @Override\n public void run() {\n // Needed for loading clojure-based jars:\n Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n pluginLoader_.loadPlugins();\n }\n }\n \n });\n \n }\n \n \n \n \n /**\n * Callback to update GUI when a change happens in the MMCore.\n */\n public class CoreEventCallback extends MMEventCallback {\n\n public CoreEventCallback() {\n super();\n }\n\n @Override\n public void onPropertiesChanged() {\n // TODO: remove test once acquisition engine is fully multithreaded\n if (engine_ != null && engine_.isAcquisitionRunning()) {\n core_.logMessage(\"Notification from MMCore ignored because acquistion is running!\", true);\n } else {\n if (ignorePropertyChanges_) {\n core_.logMessage(\"Notification from MMCore ignored since the system is still loading\", true);\n } else {\n core_.updateSystemStateCache();\n updateGUI(true);\n // update all registered listeners \n for (MMListenerInterface mmIntf : MMListeners_) {\n mmIntf.propertiesChangedAlert();\n }\n core_.logMessage(\"Notification from MMCore!\", true);\n }\n }\n }\n\n @Override\n public void onPropertyChanged(String deviceName, String propName, String propValue) {\n core_.logMessage(\"Notification for Device: \" + deviceName + \" Property: \" +\n propName + \" changed to value: \" + propValue, true);\n // update all registered listeners\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.propertyChangedAlert(deviceName, propName, propValue);\n }\n }\n\n @Override\n public void onConfigGroupChanged(String groupName, String newConfig) {\n try {\n configPad_.refreshGroup(groupName, newConfig);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.configGroupChangedAlert(groupName, newConfig);\n }\n } catch (Exception e) {\n }\n }\n \n @Override\n public void onSystemConfigurationLoaded() {\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.systemConfigurationLoaded();\n }\n }\n\n @Override\n public void onPixelSizeChanged(double newPixelSizeUm) {\n updatePixSizeUm (newPixelSizeUm);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.pixelSizeChangedAlert(newPixelSizeUm);\n }\n }\n\n @Override\n public void onStagePositionChanged(String deviceName, double pos) {\n if (deviceName.equals(zStageLabel_)) {\n updateZPos(pos);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.stagePositionChangedAlert(deviceName, pos);\n }\n }\n }\n\n @Override\n public void onStagePositionChangedRelative(String deviceName, double pos) {\n if (deviceName.equals(zStageLabel_))\n updateZPosRelative(pos);\n }\n\n @Override\n public void onXYStagePositionChanged(String deviceName, double xPos, double yPos) {\n if (deviceName.equals(xyStageLabel_)) {\n updateXYPos(xPos, yPos);\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.xyStagePositionChanged(deviceName, xPos, yPos);\n }\n }\n }\n\n @Override\n public void onXYStagePositionChangedRelative(String deviceName, double xPos, double yPos) {\n if (deviceName.equals(xyStageLabel_))\n updateXYPosRelative(xPos, yPos);\n }\n \n @Override\n public void onExposureChanged(String deviceName, double exposure) {\n if (deviceName.equals(cameraLabel_)){\n // update exposure in gui\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure)); \n }\n for (MMListenerInterface mmIntf:MMListeners_) {\n mmIntf.exposureChanged(deviceName, exposure);\n }\n }\n \n }\n\n private void handleException(Exception e, String msg) {\n String errText = \"Exception occurred: \";\n if (msg.length() > 0) {\n errText += msg + \" -- \";\n }\n if (options_.debugLogEnabled_) {\n errText += e.getMessage();\n } else {\n errText += e.toString() + \"\\n\";\n ReportingUtils.showError(e);\n }\n handleError(errText);\n }\n\n private void handleException(Exception e) {\n handleException(e, \"\");\n }\n\n private void handleError(String message) {\n if (isLiveModeOn()) {\n // Should we always stop live mode on any error?\n enableLiveMode(false);\n }\n JOptionPane.showMessageDialog(this, message);\n core_.logMessage(message);\n }\n\n public ImageWindow getImageWin() {\n return getSnapLiveWin();\n }\n\n public static VirtualAcquisitionDisplay getSimpleDisplay() {\n return simpleDisplay_;\n }\n\n public static void createSimpleDisplay(String name, ImageCache cache) throws MMScriptException {\n simpleDisplay_ = new VirtualAcquisitionDisplay(cache, name); \n }\n\n \n public void checkSimpleAcquisition() {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n int width = (int) core_.getImageWidth();\n int height = (int) core_.getImageHeight();\n int depth = (int) core_.getBytesPerPixel();\n int bitDepth = (int) core_.getImageBitDepth();\n int numCamChannels = (int) core_.getNumberOfCameraChannels();\n\n try {\n if (acquisitionExists(SIMPLE_ACQ)) {\n if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)\n || (getAcquisitionImageHeight(SIMPLE_ACQ) != height)\n || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)\n || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)\n || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window\n closeAcquisitionWindow(SIMPLE_ACQ);\n }\n }\n if (!acquisitionExists(SIMPLE_ACQ)) {\n openAcquisition(SIMPLE_ACQ, \"\", 1, numCamChannels, 1, true);\n if (numCamChannels > 1) {\n for (long i = 0; i < numCamChannels; i++) {\n String chName = core_.getCameraChannelName(i);\n int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();\n setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));\n setChannelName(SIMPLE_ACQ, (int) i, chName);\n }\n }\n initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);\n getAcquisition(SIMPLE_ACQ).promptToSave(false);\n getAcquisition(SIMPLE_ACQ).getAcquisitionWindow().getHyperImage().getWindow().toFront();\n this.updateCenterAndDragListener();\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n\n }\n\n\n public void checkSimpleAcquisition(TaggedImage image) {\n try {\n JSONObject tags = image.tags;\n int width = MDUtils.getWidth(tags);\n int height = MDUtils.getHeight(tags);\n int depth = MDUtils.getDepth(tags);\n int bitDepth = MDUtils.getBitDepth(tags);\n int numCamChannels = (int) core_.getNumberOfCameraChannels();\n\n if (acquisitionExists(SIMPLE_ACQ)) {\n if ((getAcquisitionImageWidth(SIMPLE_ACQ) != width)\n || (getAcquisitionImageHeight(SIMPLE_ACQ) != height)\n || (getAcquisitionImageByteDepth(SIMPLE_ACQ) != depth)\n || (getAcquisitionImageBitDepth(SIMPLE_ACQ) != bitDepth)\n || (getAcquisitionMultiCamNumChannels(SIMPLE_ACQ) != numCamChannels)) { //Need to close and reopen simple window\n closeAcquisitionWindow(SIMPLE_ACQ);\n // Seems that closeAcquisitionWindow also closes the acquisition...\n //closeAcquisition(SIMPLE_ACQ);\n }\n }\n if (!acquisitionExists(SIMPLE_ACQ)) {\n openAcquisition(SIMPLE_ACQ, \"\", 1, numCamChannels, 1, true);\n if (numCamChannels > 1) {\n for (long i = 0; i < numCamChannels; i++) {\n String chName = core_.getCameraChannelName(i);\n int defaultColor = multiCameraColors_[(int) i % multiCameraColors_.length].getRGB();\n setChannelColor(SIMPLE_ACQ, (int) i, getChannelColor(chName, defaultColor));\n setChannelName(SIMPLE_ACQ, (int) i, chName);\n }\n }\n initializeSimpleAcquisition(SIMPLE_ACQ, width, height, depth, bitDepth, numCamChannels);\n getAcquisition(SIMPLE_ACQ).promptToSave(false);\n getAcquisition(SIMPLE_ACQ).getAcquisitionWindow().getHyperImage().getWindow().toFront();\n this.updateCenterAndDragListener();\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n\n }\n\n public void saveChannelColor(String chName, int rgb)\n {\n if (colorPrefs_ != null) {\n colorPrefs_.putInt(\"Color_\" + chName, rgb); \n } \n }\n \n public Color getChannelColor(String chName, int defaultColor)\n { \n if (colorPrefs_ != null) {\n defaultColor = colorPrefs_.getInt(\"Color_\" + chName, defaultColor);\n }\n return new Color(defaultColor);\n }\n\n\n public void copyFromLiveModeToAlbum(VirtualAcquisitionDisplay display) throws MMScriptException, JSONException {\n ImageCache ic = display.getImageCache();\n int channels = ic.getSummaryMetadata().getInt(\"Channels\");\n if (channels == 1) {\n //RGB or monchrome\n addToAlbum(ic.getImage(0, 0, 0, 0), ic.getDisplayAndComments());\n } else {\n //multicamera\n for (int i = 0; i < channels; i++) {\n addToAlbum(ic.getImage(i, 0, 0, 0), ic.getDisplayAndComments());\n }\n }\n }\n\n private void createActiveShutterChooser(JPanel topPanel) {\n createLabel(\"Shutter\", false, topPanel, 111, 73, 158, 86); \n\n shutterComboBox_ = new JComboBox();\n shutterComboBox_.setName(\"Shutter\");\n shutterComboBox_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent arg0) {\n try {\n if (shutterComboBox_.getSelectedItem() != null) {\n core_.setShutterDevice((String) shutterComboBox_.getSelectedItem());\n }\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n });\n GUIUtils.addWithEdges(topPanel, shutterComboBox_, 170, 70, 275, 92);\n }\n\n private void createBinningChooser(JPanel topPanel) {\n createLabel(\"Binning\", false, topPanel, 111, 43, 199, 64);\n\n comboBinning_ = new JComboBox();\n comboBinning_.setName(\"Binning\");\n comboBinning_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n comboBinning_.setMaximumRowCount(4);\n comboBinning_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n changeBinning();\n }\n });\n GUIUtils.addWithEdges(topPanel, comboBinning_, 200, 43, 275, 66);\n }\n\n private void createExposureField(JPanel topPanel) {\n createLabel(\"Exposure [ms]\", false, topPanel, 111, 23, 198, 39);\n\n textFieldExp_ = new JTextField();\n textFieldExp_.addFocusListener(new FocusAdapter() {\n @Override\n public void focusLost(FocusEvent fe) {\n synchronized(shutdownLock_) {\n if (core_ != null)\n setExposure();\n }\n }\n });\n textFieldExp_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n textFieldExp_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n setExposure();\n }\n });\n GUIUtils.addWithEdges(topPanel, textFieldExp_, 203, 21, 276, 40);\n }\n\n private void toggleAutoShutter() {\n shutterLabel_ = core_.getShutterDevice();\n if (shutterLabel_.length() == 0) {\n toggleShutterButton_.setEnabled(false);\n } else {\n if (autoShutterCheckBox_.isSelected()) {\n try {\n core_.setAutoShutter(true);\n core_.setShutterOpen(false);\n toggleShutterButton_.setSelected(false);\n toggleShutterButton_.setText(\"Open\");\n toggleShutterButton_.setEnabled(false);\n } catch (Exception e2) {\n ReportingUtils.logError(e2);\n }\n } else {\n try {\n core_.setAutoShutter(false);\n core_.setShutterOpen(false);\n toggleShutterButton_.setEnabled(true);\n toggleShutterButton_.setText(\"Open\");\n } catch (Exception exc) {\n ReportingUtils.logError(exc);\n }\n }\n }\n }\n \n private void createShutterControls(JPanel topPanel) {\n autoShutterCheckBox_ = new JCheckBox();\n autoShutterCheckBox_.setFont(new Font(\"Arial\", Font.PLAIN, 10));\n autoShutterCheckBox_.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n toggleAutoShutter();\n }\n });\n autoShutterCheckBox_.setIconTextGap(6);\n autoShutterCheckBox_.setHorizontalTextPosition(SwingConstants.LEADING);\n autoShutterCheckBox_.setText(\"Auto shutter\");\n GUIUtils.addWithEdges(topPanel, autoShutterCheckBox_, 107, 96, 199, 119);\n\n toggleShutterButton_ = (JToggleButton) GUIUtils.createButton(true,\n \"toggleShutterButton\", \"Open\",\n \"Open/close the shutter\",\n new Runnable() {\n public void run() {\n toggleShutter();\n }\n }, null, topPanel, 203, 96, 275, 117); // Shutter button\n }\n\n private void createCameraSettingsWidgets(JPanel topPanel) {\n createLabel(\"Camera settings\", true, topPanel, 109, 2, 211, 22);\n createExposureField(topPanel);\n createBinningChooser(topPanel);\n createActiveShutterChooser(topPanel);\n createShutterControls(topPanel);\n }\n\n private void createConfigurationControls(JPanel topPanel) {\n createLabel(\"Configuration settings\", true, topPanel, 280, 2, 430, 22);\n\n saveConfigButton_ = (JButton) GUIUtils.createButton(false,\n \"saveConfigureButton\", \"Save\",\n \"Save current presets to the configuration file\",\n new Runnable() {\n public void run() {\n saveConfigPresets();\n }\n }, null, topPanel, -80, 2, -5, 20);\n \n configPad_ = new ConfigGroupPad();\n configPadButtonPanel_ = new ConfigPadButtonPanel();\n configPadButtonPanel_.setConfigPad(configPad_);\n configPadButtonPanel_.setGUI(MMStudioMainFrame.getInstance());\n \n configPad_.setFont(new Font(\"\", Font.PLAIN, 10));\n \n GUIUtils.addWithEdges(topPanel, configPad_, 280, 21, -4, -44);\n GUIUtils.addWithEdges(topPanel, configPadButtonPanel_, 280, -40, -4, -20);\n }\n\n private void createMainButtons(JPanel topPanel) {\n snapButton_ = (JButton) GUIUtils.createButton(false, \"Snap\", \"Snap\",\n \"Snap single image\",\n new Runnable() {\n public void run() {\n doSnap();\n }\n }, \"camera.png\", topPanel, 7, 4, 95, 25);\n\n liveButton_ = (JToggleButton) GUIUtils.createButton(true,\n \"Live\", \"Live\",\n \"Continuous live view\",\n new Runnable() {\n public void run() {\n enableLiveMode(!isLiveModeOn());\n }\n }, \"camera_go.png\", topPanel, 7, 26, 95, 47);\n\n /* toAlbumButton_ = (JButton) */ GUIUtils.createButton(false, \"Album\", \"Album\",\n \"Acquire single frame and add to an album\",\n new Runnable() {\n public void run() {\n snapAndAddToImage5D();\n }\n }, \"camera_plus_arrow.png\", topPanel, 7, 48, 95, 69);\n\n /* MDA Button = */ GUIUtils.createButton(false,\n \"Multi-D Acq.\", \"Multi-D Acq.\",\n \"Open multi-dimensional acquisition window\",\n new Runnable() {\n public void run() {\n openAcqControlDialog();\n }\n }, \"film.png\", topPanel, 7, 70, 95, 91);\n\n /* Refresh = */ GUIUtils.createButton(false, \"Refresh\", \"Refresh\",\n \"Refresh all GUI controls directly from the hardware\",\n new Runnable() {\n public void run() {\n core_.updateSystemStateCache();\n updateGUI(true);\n }\n }, \"arrow_refresh.png\", topPanel, 7, 92, 95, 113);\n }\n\n private static MetadataPanel createMetadataPanel(JPanel bottomPanel) {\n MetadataPanel metadataPanel = new MetadataPanel();\n GUIUtils.addWithEdges(bottomPanel, metadataPanel, 0, 0, 0, 0);\n metadataPanel.setBorder(BorderFactory.createEmptyBorder());\n return metadataPanel;\n }\n\n private void createPleaLabel(JPanel topPanel) {\n JLabel citePleaLabel = new JLabel(\"Please cite Micro-Manager so funding will continue!\");\n citePleaLabel.setFont(new Font(\"Arial\", Font.PLAIN, 11));\n GUIUtils.addWithEdges(topPanel, citePleaLabel, 7, 119, 270, 139);\n\n class Pleader extends Thread{\n Pleader(){\n super(\"pleader\");\n }\n @Override\n public void run(){\n try {\n ij.plugin.BrowserLauncher.openURL(\"https://micro-manager.org/wiki/Citing_Micro-Manager\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n\n }\n citePleaLabel.addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent e) {\n Pleader p = new Pleader();\n p.start();\n }\n });\n\n // add a listener to the main ImageJ window to catch it quitting out on us\n /*\n * The current version of ImageJ calls the command \"Quit\", which we \n * handle in MMStudioPlugin. Calling the closeSequence from here as well\n * leads to crashes since the core will be cleaned up by one of the two\n * threads doing the same thing. I do not know since which version of \n * ImageJ introduced this behavior - NS, 2014-04-26\n \n if (ij.IJ.getInstance() != null) {\n ij.IJ.getInstance().addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n //closeSequence(true);\n };\n });\n }\n */\n }\n\n private JSplitPane createSplitPane(int dividerPos) {\n JPanel topPanel = new JPanel();\n JPanel bottomPanel = new JPanel();\n topPanel.setLayout(new SpringLayout());\n topPanel.setMinimumSize(new Dimension(580, 195));\n bottomPanel.setLayout(new SpringLayout());\n JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,\n topPanel, bottomPanel);\n splitPane.setBorder(BorderFactory.createEmptyBorder());\n splitPane.setDividerLocation(dividerPos);\n splitPane.setResizeWeight(0.0);\n return splitPane;\n }\n\n private void createTopPanelWidgets(JPanel topPanel) {\n createMainButtons(topPanel);\n createCameraSettingsWidgets(topPanel);\n createPleaLabel(topPanel);\n createUtilityButtons(topPanel);\n createConfigurationControls(topPanel);\n labelImageDimensions_ = createLabel(\"\", false, topPanel, 5, -20, 0, 0);\n }\n\n private void createUtilityButtons(JPanel topPanel) {\n // ROI\n \n createLabel(\"ROI\", true, topPanel, 8, 140, 71, 154);\n \n setRoiButton_ = GUIUtils.createButton(false, \"setRoiButton\", null,\n \"Set Region Of Interest to selected rectangle\",\n new Runnable() {\n public void run() {\n setROI();\n }\n }, \"shape_handles.png\", topPanel, 7, 154, 37, 174);\n\n clearRoiButton_ = GUIUtils.createButton(false, \"clearRoiButton\", null,\n \"Reset Region of Interest to full frame\",\n new Runnable() {\n public void run() {\n clearROI();\n }\n }, \"arrow_out.png\", topPanel, 40, 154, 70, 174);\n \n // Zoom\n \n createLabel(\"Zoom\", true, topPanel, 81, 140, 139, 154);\n\n GUIUtils.createButton(false, \"zoomInButton\", null,\n \"Zoom in\",\n new Runnable() {\n public void run() {\n zoomIn();\n }\n }, \"zoom_in.png\", topPanel, 80, 154, 110, 174);\n\n GUIUtils.createButton(false, \"zoomOutButton\", null,\n \"Zoom out\",\n new Runnable() {\n public void run() {\n zoomOut();\n }\n }, \"zoom_out.png\", topPanel, 113, 154, 143, 174);\n\n // Profile\n \n createLabel(\"Profile\", true, topPanel, 154, 140, 217, 154);\n\n GUIUtils.createButton(false, \"lineProfileButton\", null,\n \"Open line profile window (requires line selection)\",\n new Runnable() {\n public void run() {\n openLineProfileWindow();\n }\n }, \"chart_curve.png\", topPanel, 153, 154, 183, 174);\n\n // Autofocus\n\n createLabel(\"Autofocus\", true, topPanel, 194, 140, 276, 154);\n\n autofocusNowButton_ = (JButton) GUIUtils.createButton(false,\n \"autofocusNowButton\", null,\n \"Autofocus now\",\n new Runnable() {\n public void run() {\n autofocusNow();\n }\n }, \"find.png\", topPanel, 193, 154, 223, 174);\n\n\n autofocusConfigureButton_ = (JButton) GUIUtils.createButton(false,\n \"autofocusConfigureButton\", null,\n \"Set autofocus options\",\n new Runnable() {\n public void run() {\n showAutofocusDialog();\n }\n }, \"wrench_orange.png\", topPanel, 226, 154, 256, 174);\n }\n\n private void initializeFileMenu() {\n JMenu fileMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"File\");\n\n GUIUtils.addMenuItem(fileMenu, \"Open (Virtual)...\", null,\n new Runnable() {\n public void run() {\n new Thread() {\n @Override\n public void run() {\n openAcquisitionData(false);\n }\n }.start();\n }\n });\n\n GUIUtils.addMenuItem(fileMenu, \"Open (RAM)...\", null,\n new Runnable() {\n public void run() {\n new Thread() {\n @Override\n public void run() {\n openAcquisitionData(true);\n }\n }.start();\n }\n });\n\n fileMenu.addSeparator();\n\n GUIUtils.addMenuItem(fileMenu, \"Exit\", null,\n new Runnable() {\n public void run() {\n closeSequence(false);\n }\n });\n }\n \n private void initializeHelpMenu() {\n final JMenu helpMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"Help\");\n \n GUIUtils.addMenuItem(helpMenu, \"User's Guide\", null,\n new Runnable() {\n public void run() {\n try {\n ij.plugin.BrowserLauncher.openURL(\"http://micro-manager.org/wiki/Micro-Manager_User%27s_Guide\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n });\n \n GUIUtils.addMenuItem(helpMenu, \"Configuration Guide\", null,\n new Runnable() {\n public void run() {\n try {\n ij.plugin.BrowserLauncher.openURL(\"http://micro-manager.org/wiki/Micro-Manager_Configuration_Guide\");\n } catch (IOException e1) {\n ReportingUtils.showError(e1);\n }\n }\n }); \n \n if (!systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION, false)) {\n GUIUtils.addMenuItem(helpMenu, \"Register your copy of Micro-Manager...\", null,\n new Runnable() {\n public void run() {\n try {\n RegistrationDlg regDlg = new RegistrationDlg(systemPrefs_);\n regDlg.setVisible(true);\n } catch (Exception e1) {\n ReportingUtils.showError(e1);\n }\n }\n });\n }\n\n GUIUtils.addMenuItem(helpMenu, \"Report Problem...\", null,\n new Runnable() {\n @Override\n public void run() {\n org.micromanager.diagnostics.gui.ProblemReportController.start(core_, options_);\n }\n });\n\n GUIUtils.addMenuItem(helpMenu, \"About Micromanager\", null,\n new Runnable() {\n public void run() {\n MMAboutDlg dlg = new MMAboutDlg();\n String versionInfo = \"MM Studio version: \" + MMVersion.VERSION_STRING;\n versionInfo += \"\\n\" + core_.getVersionInfo();\n versionInfo += \"\\n\" + core_.getAPIVersionInfo();\n versionInfo += \"\\nUser: \" + core_.getUserId();\n versionInfo += \"\\nHost: \" + core_.getHostName();\n dlg.setVersionInfo(versionInfo);\n dlg.setVisible(true);\n }\n });\n \n \n menuBar_.validate();\n }\n\n private void initializeToolsMenu() {\n // Tools menu\n \n final JMenu toolsMenu = GUIUtils.createMenuInMenuBar(menuBar_, \"Tools\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Refresh GUI\",\n \"Refresh all GUI controls directly from the hardware\",\n new Runnable() {\n public void run() {\n core_.updateSystemStateCache();\n updateGUI(true);\n }\n },\n \"arrow_refresh.png\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Rebuild GUI\",\n \"Regenerate Micro-Manager user interface\",\n new Runnable() {\n public void run() {\n initializeGUI();\n core_.updateSystemStateCache();\n }\n });\n \n toolsMenu.addSeparator();\n \n GUIUtils.addMenuItem(toolsMenu, \"Image Pipeline...\",\n \"Display the image processing pipeline\",\n new Runnable() {\n public void run() {\n pipelinePanel_.setVisible(true);\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Script Panel...\",\n \"Open Micro-Manager script editor window\",\n new Runnable() {\n public void run() {\n scriptPanel_.setVisible(true);\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Shortcuts...\",\n \"Create keyboard shortcuts to activate image acquisition, mark positions, or run custom scripts\",\n new Runnable() {\n public void run() {\n HotKeysDialog hk = new HotKeysDialog(guiColors_.background.get((options_.displayBackground_)));\n //hk.setBackground(guiColors_.background.get((options_.displayBackground_)));\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Device/Property Browser...\",\n \"Open new window to view and edit property values in current configuration\",\n new Runnable() {\n public void run() {\n createPropertyEditor();\n }\n });\n \n toolsMenu.addSeparator();\n\n GUIUtils.addMenuItem(toolsMenu, \"XY List...\",\n \"Open position list manager window\",\n new Runnable() {\n public void run() {\n showXYPositionList();\n }\n },\n \"application_view_list.png\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Multi-Dimensional Acquisition...\",\n \"Open multi-dimensional acquisition setup window\",\n new Runnable() {\n public void run() {\n openAcqControlDialog();\n }\n },\n \"film.png\");\n \n \n centerAndDragMenuItem_ = GUIUtils.addCheckBoxMenuItem(toolsMenu,\n \"Mouse Moves Stage (use Hand Tool)\",\n \"When enabled, double clicking or dragging in the snap/live\\n\"\n + \"window moves the XY-stage. Requires the hand tool.\",\n new Runnable() {\n public void run() {\n updateCenterAndDragListener();\n IJ.setTool(Toolbar.HAND);\n mainPrefs_.putBoolean(MOUSE_MOVES_STAGE, centerAndDragMenuItem_.isSelected());\n }\n },\n mainPrefs_.getBoolean(MOUSE_MOVES_STAGE, false));\n \n GUIUtils.addMenuItem(toolsMenu, \"Pixel Size Calibration...\",\n \"Define size calibrations specific to each objective lens. \"\n + \"When the objective in use has a calibration defined, \"\n + \"micromanager will automatically use it when \"\n + \"calculating metadata\",\n new Runnable() {\n public void run() {\n createCalibrationListDlg();\n }\n });\n /* \n GUIUtils.addMenuItem(toolsMenu, \"Image Processor Manager\",\n \"Control the order in which Image Processor plugins\"\n + \"are applied to incoming images.\",\n new Runnable() {\n public void run() {\n processorStackManager_.show();\n }\n });\n*/\n toolsMenu.addSeparator();\n\n GUIUtils.addMenuItem(toolsMenu, \"Hardware Configuration Wizard...\",\n \"Open wizard to create new hardware configuration\",\n new Runnable() {\n public void run() {\n runHardwareWizard();\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Load Hardware Configuration...\",\n \"Un-initialize current configuration and initialize new one\",\n new Runnable() {\n public void run() {\n loadConfiguration();\n initializeGUI();\n }\n });\n\n GUIUtils.addMenuItem(toolsMenu, \"Reload Hardware Configuration\",\n \"Shutdown current configuration and initialize most recently loaded configuration\",\n new Runnable() {\n public void run() {\n loadSystemConfiguration();\n initializeGUI();\n }\n });\n\n \n for (int i=0; i<5; i++)\n {\n JMenuItem configItem = new JMenuItem();\n configItem.setText(Integer.toString(i));\n switchConfigurationMenu_.add(configItem);\n }\n \n switchConfigurationMenu_.setText(\"Switch Hardware Configuration\");\n toolsMenu.add(switchConfigurationMenu_);\n switchConfigurationMenu_.setToolTipText(\"Switch between recently used configurations\");\n\n GUIUtils.addMenuItem(toolsMenu, \"Save Configuration Settings as...\",\n \"Save current configuration settings as new configuration file\",\n new Runnable() {\n public void run() {\n saveConfigPresets();\n updateChannelCombos();\n }\n });\n\n toolsMenu.addSeparator();\n\n final MMStudioMainFrame thisInstance = this;\n GUIUtils.addMenuItem(toolsMenu, \"Options...\",\n \"Set a variety of Micro-Manager configuration options\",\n new Runnable() {\n public void run() {\n final int oldBufsize = options_.circularBufferSizeMB_;\n\n OptionsDlg dlg = new OptionsDlg(options_, core_, mainPrefs_,\n thisInstance);\n dlg.setVisible(true);\n // adjust memory footprint if necessary\n if (oldBufsize != options_.circularBufferSizeMB_) {\n try {\n core_.setCircularBufferMemoryFootprint(options_.circularBufferSizeMB_);\n } catch (Exception exc) {\n ReportingUtils.showError(exc);\n }\n }\n }\n });\n }\n\n private void showRegistrationDialogMaybe() {\n // show registration dialog if not already registered\n // first check user preferences (for legacy compatibility reasons)\n boolean userReg = mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION,\n false) || mainPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);\n\n if (!userReg) {\n boolean systemReg = systemPrefs_.getBoolean(\n RegistrationDlg.REGISTRATION, false) || systemPrefs_.getBoolean(RegistrationDlg.REGISTRATION_NEVER, false);\n if (!systemReg) {\n // prompt for registration info\n RegistrationDlg dlg = new RegistrationDlg(systemPrefs_);\n dlg.setVisible(true);\n }\n }\n }\n\n private void updateSwitchConfigurationMenu() {\n switchConfigurationMenu_.removeAll();\n for (final String configFile : MRUConfigFiles_) {\n if (!configFile.equals(sysConfigFile_)) {\n GUIUtils.addMenuItem(switchConfigurationMenu_,\n configFile, null,\n new Runnable() {\n public void run() {\n sysConfigFile_ = configFile;\n loadSystemConfiguration();\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n }\n });\n }\n }\n }\n\n\n \n public final void addLiveModeListener (LiveModeListener listener) {\n if (liveModeListeners_.contains(listener)) {\n return;\n }\n liveModeListeners_.add(listener);\n }\n \n public void removeLiveModeListener(LiveModeListener listener) {\n liveModeListeners_.remove(listener);\n }\n \n public void callLiveModeListeners(boolean enable) {\n for (LiveModeListener listener : liveModeListeners_) {\n listener.liveModeEnabled(enable);\n }\n }\n \n \n /**\n * Part of ScriptInterface\n * Manipulate acquisition so that it looks like a burst\n */\n public void runBurstAcquisition() throws MMScriptException {\n double interval = engine_.getFrameIntervalMs();\n int nr = engine_.getNumFrames();\n boolean doZStack = engine_.isZSliceSettingEnabled();\n boolean doChannels = engine_.isChannelsSettingEnabled();\n engine_.enableZSliceSetting(false);\n engine_.setFrames(nr, 0);\n engine_.enableChannelsSetting(false);\n try {\n engine_.acquire();\n } catch (MMException e) {\n throw new MMScriptException(e);\n }\n engine_.setFrames(nr, interval);\n engine_.enableZSliceSetting(doZStack);\n engine_.enableChannelsSetting(doChannels);\n }\n\n public void runBurstAcquisition(int nr) throws MMScriptException {\n int originalNr = engine_.getNumFrames();\n double interval = engine_.getFrameIntervalMs();\n engine_.setFrames(nr, 0);\n this.runBurstAcquisition();\n engine_.setFrames(originalNr, interval);\n }\n\n public void runBurstAcquisition(int nr, String name, String root) throws MMScriptException {\n String originalRoot = engine_.getRootName();\n engine_.setDirName(name);\n engine_.setRootName(root);\n this.runBurstAcquisition(nr);\n engine_.setRootName(originalRoot);\n }\n\n /**\n * @Deprecated\n * @throws MMScriptException\n */\n public void startBurstAcquisition() throws MMScriptException {\n runAcquisition();\n }\n\n public boolean isBurstAcquisitionRunning() throws MMScriptException {\n if (engine_ == null)\n return false;\n return engine_.isAcquisitionRunning();\n }\n\n private void startLoadingPipelineClass() {\n Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());\n acquisitionEngine2010LoadingThread_ = new Thread(\"Pipeline Class loading thread\") {\n @Override\n public void run() {\n try {\n acquisitionEngine2010Class_ = Class.forName(\"org.micromanager.AcquisitionEngine2010\");\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n acquisitionEngine2010Class_ = null;\n }\n }\n };\n acquisitionEngine2010LoadingThread_.start();\n }\n\n\n \n /**\n * Shows images as they appear in the default display window. Uses\n * the default processor stack to process images as they arrive on\n * the rawImageQueue.\n */\n public void runDisplayThread(BlockingQueue rawImageQueue, \n final DisplayImageRoutine displayImageRoutine) {\n final BlockingQueue processedImageQueue = \n ProcessorStack.run(rawImageQueue, \n getAcquisitionEngine().getImageProcessors());\n \n new Thread(\"Display thread\") {\n @Override\n public void run() {\n try {\n TaggedImage image;\n do {\n image = processedImageQueue.take();\n if (image != TaggedImageQueue.POISON) {\n displayImageRoutine.show(image);\n }\n } while (image != TaggedImageQueue.POISON);\n } catch (InterruptedException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }.start();\n }\n\n\n private static JLabel createLabel(String text, boolean big,\n JPanel parentPanel, int west, int north, int east, int south) {\n final JLabel label = new JLabel();\n label.setFont(new Font(\"Arial\",\n big ? Font.BOLD : Font.PLAIN,\n big ? 11 : 10));\n label.setText(text);\n GUIUtils.addWithEdges(parentPanel, label, west, north, east, south);\n return label;\n }\n\n public interface DisplayImageRoutine {\n public void show(TaggedImage image);\n }\n \n /**\n * used to store contrast settings to be later used for initialization of contrast of new windows.\n * Shouldn't be called by loaded data sets, only\n * ones that have been acquired\n */\n public void saveChannelHistogramSettings(String channelGroup, String channel, boolean mda, \n HistogramSettings settings) {\n String type = mda ? \"MDA_\" : \"SnapLive_\";\n if (options_.syncExposureMainAndMDA_) {\n type = \"\"; //only one group of contrast settings\n }\n contrastPrefs_.putInt(\"ContrastMin_\" + channelGroup + \"_\" + type + channel, settings.min_);\n contrastPrefs_.putInt(\"ContrastMax_\" + channelGroup + \"_\" + type + channel, settings.max_);\n contrastPrefs_.putDouble(\"ContrastGamma_\" + channelGroup + \"_\" + type + channel, settings.gamma_);\n contrastPrefs_.putInt(\"ContrastHistMax_\" + channelGroup + \"_\" + type + channel, settings.histMax_);\n contrastPrefs_.putInt(\"ContrastHistDisplayMode_\" + channelGroup + \"_\" + type + channel, settings.displayMode_);\n }\n\n public HistogramSettings loadStoredChannelHisotgramSettings(String channelGroup, String channel, boolean mda) {\n String type = mda ? \"MDA_\" : \"SnapLive_\";\n if (options_.syncExposureMainAndMDA_) {\n type = \"\"; //only one group of contrast settings\n }\n return new HistogramSettings(\n contrastPrefs_.getInt(\"ContrastMin_\" + channelGroup + \"_\" + type + channel,0),\n contrastPrefs_.getInt(\"ContrastMax_\" + channelGroup + \"_\" + type + channel, 65536),\n contrastPrefs_.getDouble(\"ContrastGamma_\" + channelGroup + \"_\" + type + channel, 1.0),\n contrastPrefs_.getInt(\"ContrastHistMax_\" + channelGroup + \"_\" + type + channel, -1),\n contrastPrefs_.getInt(\"ContrastHistDisplayMode_\" + channelGroup + \"_\" + type + channel, 1) );\n }\n\n private void setExposure() {\n try {\n if (!isLiveModeOn()) {\n core_.setExposure(NumberUtils.displayStringToDouble(\n textFieldExp_.getText()));\n } else {\n liveModeTimer_.stop();\n core_.setExposure(NumberUtils.displayStringToDouble(\n textFieldExp_.getText()));\n try {\n liveModeTimer_.begin();\n } catch (Exception e) {\n ReportingUtils.showError(\"Couldn't restart live mode\");\n liveModeTimer_.stop();\n }\n }\n \n\n // Display the new exposure time\n double exposure = core_.getExposure();\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));\n \n // update current channel in MDA window with this exposure\n String channelGroup = core_.getChannelGroup();\n String channel = core_.getCurrentConfigFromCache(channelGroup);\n if (!channel.equals(\"\") ) {\n exposurePrefs_.putDouble(\"Exposure_\" + channelGroup + \"_\"\n + channel, exposure);\n if (options_.syncExposureMainAndMDA_) {\n getAcqDlg().setChannelExposureTime(channelGroup, channel, exposure);\n }\n }\n \n\n } catch (Exception exp) {\n // Do nothing.\n }\n }\n \n\n\n public double getPreferredWindowMag() {\n return options_.windowMag_;\n }\n\n public boolean getMetadataFileWithMultipageTiff() {\n return options_.mpTiffMetadataFile_;\n }\n\n public boolean getSeparateFilesForPositionsMPTiff() {\n return options_.mpTiffSeparateFilesForPositions_;\n }\n \n @Override\n public boolean getHideMDADisplayOption() {\n return options_.hideMDADisplay_;\n }\n\n private void updateTitle() {\n this.setTitle(MICRO_MANAGER_TITLE + \" \" + MMVersion.VERSION_STRING + \" - \" + sysConfigFile_);\n }\n\n public void updateLineProfile() {\n if (WindowManager.getCurrentWindow() == null || profileWin_ == null\n || !profileWin_.isShowing()) {\n return;\n }\n\n calculateLineProfileData(WindowManager.getCurrentImage());\n profileWin_.setData(lineProfileData_);\n }\n\n private void openLineProfileWindow() {\n if (WindowManager.getCurrentWindow() == null || WindowManager.getCurrentWindow().isClosed()) {\n return;\n }\n calculateLineProfileData(WindowManager.getCurrentImage());\n if (lineProfileData_ == null) {\n return;\n }\n profileWin_ = new GraphFrame();\n profileWin_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n profileWin_.setData(lineProfileData_);\n profileWin_.setAutoScale();\n profileWin_.setTitle(\"Live line profile\");\n profileWin_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(profileWin_);\n profileWin_.setVisible(true);\n }\n\n @Override\n public Rectangle getROI() throws MMScriptException {\n // ROI values are given as x,y,w,h in individual one-member arrays (pointers in C++):\n int[][] a = new int[4][1];\n try {\n core_.getROI(a[0], a[1], a[2], a[3]);\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n // Return as a single array with x,y,w,h:\n return new Rectangle(a[0][0], a[1][0], a[2][0], a[3][0]);\n }\n\n private void calculateLineProfileData(ImagePlus imp) {\n // generate line profile\n Roi roi = imp.getRoi();\n if (roi == null || !roi.isLine()) {\n\n // if there is no line ROI, create one\n Rectangle r = imp.getProcessor().getRoi();\n int iWidth = r.width;\n int iHeight = r.height;\n int iXROI = r.x;\n int iYROI = r.y;\n if (roi == null) {\n iXROI += iWidth / 2;\n iYROI += iHeight / 2;\n }\n\n roi = new Line(iXROI - iWidth / 4, iYROI - iWidth / 4, iXROI\n + iWidth / 4, iYROI + iHeight / 4);\n imp.setRoi(roi);\n roi = imp.getRoi();\n }\n\n ImageProcessor ip = imp.getProcessor();\n ip.setInterpolate(true);\n Line line = (Line) roi;\n\n if (lineProfileData_ == null) {\n lineProfileData_ = new GraphData();\n }\n lineProfileData_.setData(line.getPixels());\n }\n\n \n\n private void setROI() {\n ImagePlus curImage = WindowManager.getCurrentImage();\n if (curImage == null) {\n return;\n }\n\n Roi roi = curImage.getRoi();\n \n try {\n if (roi == null) {\n // if there is no ROI, create one\n Rectangle r = curImage.getProcessor().getRoi();\n int iWidth = r.width;\n int iHeight = r.height;\n int iXROI = r.x;\n int iYROI = r.y;\n if (roi == null) {\n iWidth /= 2;\n iHeight /= 2;\n iXROI += iWidth / 2;\n iYROI += iHeight / 2;\n }\n\n curImage.setRoi(iXROI, iYROI, iWidth, iHeight);\n roi = curImage.getRoi();\n }\n\n if (roi.getType() != Roi.RECTANGLE) {\n handleError(\"ROI must be a rectangle.\\nUse the ImageJ rectangle tool to draw the ROI.\");\n return;\n }\n\n Rectangle r = roi.getBounds();\n // if we already had an ROI defined, correct for the offsets\n Rectangle cameraR = getROI();\n r.x += cameraR.x;\n r.y += cameraR.y;\n // Stop (and restart) live mode if it is running\n setROI(r);\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n private void clearROI() {\n try {\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n core_.clearROI();\n updateStaticInfo();\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n /**\n * Returns instance of the core uManager object;\n */\n @Override\n public CMMCore getMMCore() {\n return core_;\n }\n\n /**\n * Returns singleton instance of MMStudioMainFrame\n */\n public static MMStudioMainFrame getInstance() {\n return gui_;\n }\n\n public MetadataPanel getMetadataPanel() {\n return metadataPanel_;\n }\n\n public final void setExitStrategy(boolean closeOnExit) {\n if (closeOnExit) {\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n else {\n setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n }\n }\n\n @Override\n public void saveConfigPresets() {\n MicroscopeModel model = new MicroscopeModel();\n try {\n model.loadFromFile(sysConfigFile_);\n model.createSetupConfigsFromHardware(core_);\n model.createResolutionsFromHardware(core_);\n File f = FileDialogs.save(this, \"Save the configuration file\", MM_CONFIG_FILE);\n if (f != null) {\n model.saveToFile(f.getAbsolutePath());\n sysConfigFile_ = f.getAbsolutePath();\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n configChanged_ = false;\n setConfigSaveButtonStatus(configChanged_);\n updateTitle();\n }\n } catch (MMConfigFileException e) {\n ReportingUtils.showError(e);\n }\n }\n\n protected void setConfigSaveButtonStatus(boolean changed) {\n saveConfigButton_.setEnabled(changed);\n }\n\n public String getAcqDirectory() {\n return openAcqDirectory_;\n }\n \n /**\n * Get currently used configuration file\n * @return - Path to currently used configuration file\n */\n public String getSysConfigFile() {\n return sysConfigFile_;\n }\n\n public void setAcqDirectory(String dir) {\n openAcqDirectory_ = dir;\n }\n\n /**\n * Open an existing acquisition directory and build viewer window.\n *\n */\n public void openAcquisitionData(boolean inRAM) {\n\n // choose the directory\n // --------------------\n File f = FileDialogs.openDir(this, \"Please select an image data set\", MM_DATA_SET);\n if (f != null) {\n if (f.isDirectory()) {\n openAcqDirectory_ = f.getAbsolutePath();\n } else {\n openAcqDirectory_ = f.getParent();\n }\n String acq = null;\n try {\n acq = openAcquisitionData(openAcqDirectory_, inRAM);\n } catch (MMScriptException ex) {\n ReportingUtils.showError(ex);\n } finally {\n try {\n acqMgr_.closeAcquisition(acq);\n } catch (MMScriptException ex) {\n ReportingUtils.logError(ex);\n }\n }\n \n }\n }\n\n @Override\n public String openAcquisitionData(String dir, boolean inRAM, boolean show) \n throws MMScriptException {\n String rootDir = new File(dir).getAbsolutePath();\n String name = new File(dir).getName();\n rootDir = rootDir.substring(0, rootDir.length() - (name.length() + 1));\n name = acqMgr_.getUniqueAcquisitionName(name);\n acqMgr_.openAcquisition(name, rootDir, show, !inRAM, true);\n try {\n getAcquisition(name).initialize();\n } catch (MMScriptException mex) {\n acqMgr_.closeAcquisition(name);\n throw (mex);\n }\n \n return name;\n }\n\n /**\n * Opens an existing data set. Shows the acquisition in a window.\n * @return The acquisition object.\n */\n @Override\n public String openAcquisitionData(String dir, boolean inRam) throws MMScriptException {\n return openAcquisitionData(dir, inRam, true);\n }\n\n protected void zoomOut() {\n ImageWindow curWin = WindowManager.getCurrentWindow();\n if (curWin != null) {\n ImageCanvas canvas = curWin.getCanvas();\n Rectangle r = canvas.getBounds();\n canvas.zoomOut(r.width / 2, r.height / 2);\n\n VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());\n if (vad != null) {\n vad.storeWindowSizeAfterZoom(curWin);\n vad.updateWindowTitleAndStatus();\n }\n }\n }\n\n protected void zoomIn() {\n ImageWindow curWin = WindowManager.getCurrentWindow();\n if (curWin != null) {\n ImageCanvas canvas = curWin.getCanvas();\n Rectangle r = canvas.getBounds();\n canvas.zoomIn(r.width / 2, r.height / 2);\n \n VirtualAcquisitionDisplay vad = VirtualAcquisitionDisplay.getDisplay(curWin.getImagePlus());\n if (vad != null) {\n vad.storeWindowSizeAfterZoom(curWin);\n vad.updateWindowTitleAndStatus();\n } \n }\n }\n\n protected void changeBinning() {\n try {\n boolean liveRunning = false;\n if (isLiveModeOn() ) {\n liveRunning = true;\n enableLiveMode(false);\n } \n \n if (isCameraAvailable()) {\n Object item = comboBinning_.getSelectedItem();\n if (item != null) {\n core_.setProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning(), item.toString());\n }\n }\n updateStaticInfo();\n\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n\n \n }\n\n private void createPropertyEditor() {\n if (propertyBrowser_ != null) {\n propertyBrowser_.dispose();\n }\n\n propertyBrowser_ = new PropertyEditor();\n propertyBrowser_.setGui(this);\n propertyBrowser_.setVisible(true);\n propertyBrowser_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n propertyBrowser_.setCore(core_);\n }\n\n private void createCalibrationListDlg() {\n if (calibrationListDlg_ != null) {\n calibrationListDlg_.dispose();\n }\n\n calibrationListDlg_ = new CalibrationListDlg(core_);\n calibrationListDlg_.setVisible(true);\n calibrationListDlg_.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n calibrationListDlg_.setParentGUI(this);\n }\n\n public CalibrationListDlg getCalibrationListDlg() {\n if (calibrationListDlg_ == null) {\n createCalibrationListDlg();\n }\n return calibrationListDlg_;\n }\n\n private void createScriptPanel() {\n if (scriptPanel_ == null) {\n scriptPanel_ = new ScriptPanel(core_, options_, this);\n scriptPanel_.insertScriptingObject(SCRIPT_CORE_OBJECT, core_);\n scriptPanel_.insertScriptingObject(SCRIPT_ACQENG_OBJECT, engine_);\n scriptPanel_.setParentGUI(this);\n scriptPanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(scriptPanel_);\n }\n }\n\n private void createPipelinePanel() {\n if (pipelinePanel_ == null) {\n pipelinePanel_ = new PipelinePanel(this, engine_);\n pipelinePanel_.setBackground(guiColors_.background.get((options_.displayBackground_)));\n addMMBackgroundListener(pipelinePanel_);\n }\n }\n\n /**\n * Updates Status line in main window from cached values\n */\n private void updateStaticInfoFromCache() {\n String dimText = \"Image info (from camera): \" + staticInfo_.width_ + \" X \" + staticInfo_.height_ + \" X \"\n + staticInfo_.bytesPerPixel_ + \", Intensity range: \" + staticInfo_.imageBitDepth_ + \" bits\";\n dimText += \", \" + TextUtils.FMT0.format(staticInfo_.pixSizeUm_ * 1000) + \"nm/pix\";\n if (zStageLabel_.length() > 0) {\n dimText += \", Z=\" + TextUtils.FMT2.format(staticInfo_.zPos_) + \"um\";\n }\n if (xyStageLabel_.length() > 0) {\n dimText += \", XY=(\" + TextUtils.FMT2.format(staticInfo_.x_) + \",\" + TextUtils.FMT2.format(staticInfo_.y_) + \")um\";\n }\n\n labelImageDimensions_.setText(dimText);\n }\n\n public void updateXYPos(double x, double y) {\n staticInfo_.x_ = x;\n staticInfo_.y_ = y;\n\n updateStaticInfoFromCache();\n }\n\n public void updateZPos(double z) {\n staticInfo_.zPos_ = z;\n\n updateStaticInfoFromCache();\n }\n\n public void updateXYPosRelative(double x, double y) {\n staticInfo_.x_ += x;\n staticInfo_.y_ += y;\n\n updateStaticInfoFromCache();\n }\n\n public void updateZPosRelative(double z) {\n staticInfo_.zPos_ += z;\n\n updateStaticInfoFromCache();\n }\n\n public void updateXYStagePosition(){\n\n double x[] = new double[1];\n double y[] = new double[1];\n try {\n if (xyStageLabel_.length() > 0) \n core_.getXYPosition(xyStageLabel_, x, y);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n\n staticInfo_.x_ = x[0];\n staticInfo_.y_ = y[0];\n updateStaticInfoFromCache();\n }\n\n private void updatePixSizeUm (double pixSizeUm) {\n staticInfo_.pixSizeUm_ = pixSizeUm;\n\n updateStaticInfoFromCache();\n }\n\n private void updateStaticInfo() {\n double zPos = 0.0;\n double x[] = new double[1];\n double y[] = new double[1];\n\n try {\n if (zStageLabel_.length() > 0) {\n zPos = core_.getPosition(zStageLabel_);\n }\n if (xyStageLabel_.length() > 0) {\n core_.getXYPosition(xyStageLabel_, x, y);\n }\n } catch (Exception e) {\n handleException(e);\n }\n\n staticInfo_.width_ = core_.getImageWidth();\n staticInfo_.height_ = core_.getImageHeight();\n staticInfo_.bytesPerPixel_ = core_.getBytesPerPixel();\n staticInfo_.imageBitDepth_ = core_.getImageBitDepth();\n staticInfo_.pixSizeUm_ = core_.getPixelSizeUm();\n staticInfo_.zPos_ = zPos;\n staticInfo_.x_ = x[0];\n staticInfo_.y_ = y[0];\n\n updateStaticInfoFromCache();\n }\n\n public void toggleShutter() {\n try {\n if (!toggleShutterButton_.isEnabled())\n return;\n toggleShutterButton_.requestFocusInWindow();\n if (toggleShutterButton_.getText().equals(\"Open\")) {\n setShutterButton(true);\n core_.setShutterOpen(true);\n } else {\n core_.setShutterOpen(false);\n setShutterButton(false);\n }\n } catch (Exception e1) {\n ReportingUtils.showError(e1);\n }\n }\n\n private void updateCenterAndDragListener() {\n if (centerAndDragMenuItem_.isSelected()) {\n centerAndDragListener_.start();\n } else {\n centerAndDragListener_.stop();\n }\n }\n \n private void setShutterButton(boolean state) {\n if (state) {\n toggleShutterButton_.setText(\"Close\");\n } else {\n toggleShutterButton_.setText(\"Open\");\n }\n }\n \n \n private void checkPosListDlg() {\n if (posListDlg_ == null) {\n posListDlg_ = new PositionListDlg(core_, this, posList_, \n acqControlWin_,options_);\n GUIUtils.recallPosition(posListDlg_);\n posListDlg_.setBackground(gui_.getBackgroundColor());\n gui_.addMMBackgroundListener(posListDlg_);\n posListDlg_.addListeners();\n }\n }\n \n\n // //////////////////////////////////////////////////////////////////////////\n // public interface available for scripting access\n // //////////////////////////////////////////////////////////////////////////\n @Override\n public void snapSingleImage() {\n doSnap();\n }\n\n public Object getPixels() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null) {\n return ip.getProcessor().getPixels();\n }\n\n return null;\n }\n\n public void setPixels(Object obj) {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip == null) {\n return;\n }\n ip.getProcessor().setPixels(obj);\n }\n\n public int getImageHeight() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getHeight();\n return 0;\n }\n\n public int getImageWidth() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getWidth();\n return 0;\n }\n\n public int getImageDepth() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null)\n return ip.getBitDepth();\n return 0;\n }\n\n public ImageProcessor getImageProcessor() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip == null)\n return null;\n return ip.getProcessor();\n }\n\n private boolean isCameraAvailable() {\n return cameraLabel_.length() > 0;\n }\n\n /**\n * Part of ScriptInterface API\n * Opens the XYPositionList when it is not opened\n * Adds the current position to the list (same as pressing the \"Mark\" button)\n */\n @Override\n public void markCurrentPosition() {\n if (posListDlg_ == null) {\n showXYPositionList();\n }\n if (posListDlg_ != null) {\n posListDlg_.markPosition();\n }\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n @Deprecated\n public AcqControlDlg getAcqDlg() {\n return acqControlWin_;\n }\n\n \n /**\n * Implements ScriptInterface\n */\n @Override\n @Deprecated\n public PositionListDlg getXYPosListDlg() {\n checkPosListDlg();\n return posListDlg_;\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n public boolean isAcquisitionRunning() {\n if (engine_ == null)\n return false;\n return engine_.isAcquisitionRunning();\n }\n\n /**\n * Implements ScriptInterface\n */\n @Override\n public boolean versionLessThan(String version) throws MMScriptException {\n try {\n String[] v = MMVersion.VERSION_STRING.split(\" \", 2);\n String[] m = v[0].split(\"\\\\.\", 3);\n String[] v2 = version.split(\" \", 2);\n String[] m2 = v2[0].split(\"\\\\.\", 3);\n for (int i=0; i < 3; i++) {\n if (Integer.parseInt(m[i]) < Integer.parseInt(m2[i])) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return true;\n }\n if (Integer.parseInt(m[i]) > Integer.parseInt(m2[i])) {\n return false;\n }\n }\n if (v2.length < 2 || v2[1].equals(\"\") )\n return false;\n if (v.length < 2 ) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return true;\n }\n if (Integer.parseInt(v[1]) < Integer.parseInt(v2[1])) {\n ReportingUtils.showError(\"This code needs Micro-Manager version \" + version + \" or greater\");\n return false;\n }\n return true;\n\n } catch (Exception ex) {\n throw new MMScriptException (\"Format of version String should be \\\"a.b.c\\\"\");\n }\n } \n\n @Override\n public boolean isLiveModeOn() {\n return liveModeTimer_ != null && liveModeTimer_.isRunning();\n }\n \n public LiveModeTimer getLiveModeTimer() {\n if (liveModeTimer_ == null) {\n liveModeTimer_ = new LiveModeTimer();\n }\n return liveModeTimer_;\n }\n \n \n\n public void updateButtonsForLiveMode(boolean enable) {\n autoShutterCheckBox_.setEnabled(!enable);\n if (core_.getAutoShutter()) {\n toggleShutterButton_.setText(enable ? \"Close\" : \"Open\" );\n }\n snapButton_.setEnabled(!enable);\n //toAlbumButton_.setEnabled(!enable);\n liveButton_.setIcon(enable ? SwingResourceManager.getIcon(MMStudioMainFrame.class,\n \"/org/micromanager/icons/cancel.png\")\n : SwingResourceManager.getIcon(MMStudioMainFrame.class,\n \"/org/micromanager/icons/camera_go.png\"));\n liveButton_.setSelected(false);\n liveButton_.setText(enable ? \"Stop Live\" : \"Live\");\n \n }\n\n public boolean getLiveMode() {\n return isLiveModeOn();\n }\n\n public boolean updateImage() {\n try {\n if (isLiveModeOn()) {\n enableLiveMode(false);\n return true; // nothing to do, just show the last image\n }\n\n if (WindowManager.getCurrentWindow() == null) {\n return false;\n }\n\n ImagePlus ip = WindowManager.getCurrentImage();\n \n core_.snapImage();\n Object img = core_.getImage();\n\n ip.getProcessor().setPixels(img);\n ip.updateAndRepaintWindow();\n\n if (!isCurrentImageFormatSupported()) {\n return false;\n }\n \n updateLineProfile();\n } catch (Exception e) {\n ReportingUtils.showError(e);\n return false;\n }\n\n return true;\n }\n\n public boolean displayImage(final Object pixels) {\n if (pixels instanceof TaggedImage) {\n return displayTaggedImage((TaggedImage) pixels, true);\n } else {\n return displayImage(pixels, true);\n }\n }\n\n\n public boolean displayImage(final Object pixels, boolean wait) {\n checkSimpleAcquisition();\n try { \n int width = getAcquisition(SIMPLE_ACQ).getWidth();\n int height = getAcquisition(SIMPLE_ACQ).getHeight();\n int byteDepth = getAcquisition(SIMPLE_ACQ).getByteDepth(); \n TaggedImage ti = ImageUtils.makeTaggedImage(pixels, 0, 0, 0,0, width, height, byteDepth);\n simpleDisplay_.getImageCache().putImage(ti);\n simpleDisplay_.showImage(ti, wait);\n return true;\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n return false;\n }\n }\n\n public boolean displayImageWithStatusLine(Object pixels, String statusLine) {\n boolean ret = displayImage(pixels);\n simpleDisplay_.displayStatusLine(statusLine);\n return ret;\n }\n\n public void displayStatusLine(String statusLine) {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (!(ip.getWindow() instanceof VirtualAcquisitionDisplay.DisplayWindow)) {\n return;\n }\n VirtualAcquisitionDisplay.getDisplay(ip).displayStatusLine(statusLine);\n }\n\n private boolean isCurrentImageFormatSupported() {\n boolean ret = false;\n long channels = core_.getNumberOfComponents();\n long bpp = core_.getBytesPerPixel();\n\n if (channels > 1 && channels != 4 && bpp != 1) {\n handleError(\"Unsupported image format.\");\n } else {\n ret = true;\n }\n return ret;\n }\n\n public void doSnap() {\n doSnap(false);\n }\n\n public void doSnap(final boolean album) {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n\n BlockingQueue snapImageQueue = \n new LinkedBlockingQueue();\n \n try {\n core_.snapImage();\n long c = core_.getNumberOfCameraChannels();\n runDisplayThread(snapImageQueue, new DisplayImageRoutine() {\n @Override\n public void show(final TaggedImage image) {\n if (album) {\n try {\n addToAlbum(image);\n } catch (MMScriptException ex) {\n ReportingUtils.showError(ex);\n }\n } else {\n displayImage(image);\n }\n }\n\n });\n \n for (int i = 0; i < c; ++i) {\n TaggedImage img = core_.getTaggedImage(i);\n img.tags.put(\"Channels\", c);\n snapImageQueue.put(img);\n }\n \n snapImageQueue.put(TaggedImageQueue.POISON);\n\n if (simpleDisplay_ != null) {\n ImagePlus imgp = simpleDisplay_.getImagePlus();\n if (imgp != null) {\n ImageWindow win = imgp.getWindow();\n if (win != null) {\n win.toFront();\n }\n }\n }\n } catch (Exception ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n /**\n * Is this function still needed? It does some magic with tags. I found \n * it to do harmful thing with tags when a Multi-Camera device is\n * present (that issue is now fixed).\n */\n public void normalizeTags(TaggedImage ti) {\n if (ti != TaggedImageQueue.POISON) {\n int channel = 0;\n try {\n\n if (ti.tags.has(\"ChannelIndex\")) {\n channel = MDUtils.getChannelIndex(ti.tags);\n }\n MDUtils.setChannelIndex(ti.tags, channel);\n MDUtils.setPositionIndex(ti.tags, 0);\n MDUtils.setSliceIndex(ti.tags, 0);\n MDUtils.setFrameIndex(ti.tags, 0);\n \n } catch (JSONException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }\n\n private boolean displayTaggedImage(TaggedImage ti, boolean update) {\n try {\n checkSimpleAcquisition(ti);\n setCursor(new Cursor(Cursor.WAIT_CURSOR));\n ti.tags.put(\"Summary\", getAcquisition(SIMPLE_ACQ).getSummaryMetadata());\n addStagePositionToTags(ti);\n addImage(SIMPLE_ACQ, ti, update, true);\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n return false;\n }\n if (update) {\n setCursor(new Cursor(Cursor.DEFAULT_CURSOR));\n updateLineProfile();\n }\n return true;\n }\n \n public void addStagePositionToTags(TaggedImage ti) throws JSONException {\n if (gui_.xyStageLabel_.length() > 0) {\n ti.tags.put(\"XPositionUm\", gui_.staticInfo_.x_);\n ti.tags.put(\"YPositionUm\", gui_.staticInfo_.y_);\n }\n if (gui_.zStageLabel_.length() > 0) {\n ti.tags.put(\"ZPositionUm\", gui_.staticInfo_.zPos_);\n }\n }\n\n private void configureBinningCombo() throws Exception {\n if (cameraLabel_.length() > 0) {\n ActionListener[] listeners;\n\n // binning combo\n if (comboBinning_.getItemCount() > 0) {\n comboBinning_.removeAllItems();\n }\n StrVector binSizes = core_.getAllowedPropertyValues(\n cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n listeners = comboBinning_.getActionListeners();\n for (int i = 0; i < listeners.length; i++) {\n comboBinning_.removeActionListener(listeners[i]);\n }\n for (int i = 0; i < binSizes.size(); i++) {\n comboBinning_.addItem(binSizes.get(i));\n }\n\n comboBinning_.setMaximumRowCount((int) binSizes.size());\n if (binSizes.isEmpty()) {\n comboBinning_.setEditable(true);\n } else {\n comboBinning_.setEditable(false);\n }\n\n for (int i = 0; i < listeners.length; i++) {\n comboBinning_.addActionListener(listeners[i]);\n }\n }\n }\n\n public void initializeGUI() {\n try {\n\n // establish device roles\n cameraLabel_ = core_.getCameraDevice();\n shutterLabel_ = core_.getShutterDevice();\n zStageLabel_ = core_.getFocusDevice();\n xyStageLabel_ = core_.getXYStageDevice();\n engine_.setZStageDevice(zStageLabel_); \n \n configureBinningCombo();\n\n // active shutter combo\n try {\n shutters_ = core_.getLoadedDevicesOfType(DeviceType.ShutterDevice);\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n\n if (shutters_ != null) {\n String items[] = new String[(int) shutters_.size()];\n for (int i = 0; i < shutters_.size(); i++) {\n items[i] = shutters_.get(i);\n }\n\n GUIUtils.replaceComboContents(shutterComboBox_, items);\n String activeShutter = core_.getShutterDevice();\n if (activeShutter != null) {\n shutterComboBox_.setSelectedItem(activeShutter);\n } else {\n shutterComboBox_.setSelectedItem(\"\");\n }\n }\n\n // Autofocus\n autofocusConfigureButton_.setEnabled(afMgr_.getDevice() != null);\n autofocusNowButton_.setEnabled(afMgr_.getDevice() != null);\n\n // Rebuild stage list in XY PositinList\n if (posListDlg_ != null) {\n posListDlg_.rebuildAxisList();\n }\n\n updateGUI(true);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n\n \n /**\n * Adds plugin_ items to the plugins menu\n * Adds submenus (currently only 1 level deep)\n * @param plugin_ - plugin_ to be added to the menu\n */\n public void addPluginToMenu(final PluginLoader.PluginItem plugin) {\n List path = plugin.getMenuPath();\n if (path.size() == 1) {\n GUIUtils.addMenuItem(pluginMenu_, plugin.getMenuItem(), plugin.getTooltip(),\n new Runnable() {\n public void run() {\n ReportingUtils.logMessage(\"Plugin command: \" + plugin.getMenuItem());\n MMStudioMainFrame localFrame = MMStudioMainFrame.this;\n plugin.instantiate();\n switch (plugin.getPluginType()) {\n case PLUGIN_STANDARD:\n // Standard plugin; create its UI.\n ((MMPlugin) plugin.getPlugin()).show();\n break;\n case PLUGIN_PROCESSOR:\n // Processor plugin; check for existing processor of \n // this type and show its UI if applicable; otherwise\n // create a new one.\n MMProcessorPlugin procPlugin = (MMProcessorPlugin) plugin.getPlugin();\n String procName = PluginLoader.getNameForPluginClass(procPlugin.getClass());\n DataProcessor pipelineProcessor = localFrame.engine_.getProcessorRegisteredAs(procName);\n if (pipelineProcessor == null) {\n // No extant processor of this type; make a new one,\n // which automatically adds it to the pipeline.\n pipelineProcessor = localFrame.engine_.makeProcessor(procName, localFrame);\n }\n if (pipelineProcessor != null) {\n // Show the GUI for this processor. It could be null\n // if making the processor, above, failed.\n pipelineProcessor.makeConfigurationGUI();\n }\n break;\n default:\n // Unrecognized plugin type; just skip it. \n ReportingUtils.logError(\"Unrecognized plugin type \" + plugin.getPluginType());\n }\n }\n });\n }\n if (path.size() == 2) {\n if (pluginSubMenus_ == null) {\n pluginSubMenus_ = new HashMap();\n }\n String groupName = path.get(0);\n JMenu submenu = pluginSubMenus_.get(groupName);\n if (submenu == null) {\n submenu = new JMenu(groupName);\n pluginSubMenus_.put(groupName, submenu);\n submenu.validate();\n pluginMenu_.add(submenu);\n }\n GUIUtils.addMenuItem(submenu, plugin.getMenuItem(), plugin.getTooltip(),\n new Runnable() {\n public void run() {\n ReportingUtils.logMessage(\"Plugin command: \" + plugin.getMenuItem());\n plugin.instantiate();\n ((MMPlugin) plugin.getPlugin()).show();\n }\n });\n }\n \n pluginMenu_.validate();\n menuBar_.validate();\n }\n \n public void updateGUI(boolean updateConfigPadStructure) {\n updateGUI(updateConfigPadStructure, false);\n }\n\n public void updateGUI(boolean updateConfigPadStructure, boolean fromCache) {\n\n try {\n // establish device roles\n cameraLabel_ = core_.getCameraDevice();\n shutterLabel_ = core_.getShutterDevice();\n zStageLabel_ = core_.getFocusDevice();\n xyStageLabel_ = core_.getXYStageDevice();\n\n afMgr_.refresh();\n\n // camera settings\n if (isCameraAvailable()) {\n double exp = core_.getExposure();\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exp));\n configureBinningCombo();\n String binSize;\n if (fromCache) {\n binSize = core_.getPropertyFromCache(cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n } else {\n binSize = core_.getProperty(cameraLabel_, MMCoreJ.getG_Keyword_Binning());\n }\n GUIUtils.setComboSelection(comboBinning_, binSize);\n }\n\n if (liveModeTimer_ == null || !liveModeTimer_.isRunning()) {\n autoShutterCheckBox_.setSelected(core_.getAutoShutter());\n boolean shutterOpen = core_.getShutterOpen();\n setShutterButton(shutterOpen);\n if (autoShutterCheckBox_.isSelected()) {\n toggleShutterButton_.setEnabled(false);\n } else {\n toggleShutterButton_.setEnabled(true);\n }\n }\n\n // active shutter combo\n if (shutters_ != null) {\n String activeShutter = core_.getShutterDevice();\n if (activeShutter != null) {\n shutterComboBox_.setSelectedItem(activeShutter);\n } else {\n shutterComboBox_.setSelectedItem(\"\");\n }\n }\n\n // state devices\n if (updateConfigPadStructure && (configPad_ != null)) {\n configPad_.refreshStructure(fromCache);\n // Needed to update read-only properties. May slow things down...\n if (!fromCache)\n core_.updateSystemStateCache();\n }\n\n // update Channel menus in Multi-dimensional acquisition dialog\n updateChannelCombos();\n\n // update list of pixel sizes in pixel size configuration window\n if (calibrationListDlg_ != null) {\n calibrationListDlg_.refreshCalibrations();\n }\n if (propertyBrowser_ != null) {\n propertyBrowser_.refresh();\n }\n\n } catch (Exception e) {\n ReportingUtils.logError(e);\n }\n\n updateStaticInfo();\n updateTitle();\n\n }\n\n //TODO: Deprecated @Override\n public boolean okToAcquire() {\n return !isLiveModeOn();\n }\n\n //TODO: Deprecated @Override\n public void stopAllActivity() {\n if (this.acquisitionEngine2010_ != null) {\n this.acquisitionEngine2010_.stop();\n }\n enableLiveMode(false);\n }\n\n /**\n * Cleans up resources while shutting down \n * \n * @param calledByImageJ\n * @return flag indicating success. Shut down should abort when flag is false \n */\n private boolean cleanupOnClose(boolean calledByImageJ) {\n // Save config presets if they were changed.\n if (configChanged_) {\n Object[] options = {\"Yes\", \"No\"};\n int n = JOptionPane.showOptionDialog(null,\n \"Save Changed Configuration?\", \"Micro-Manager\",\n JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,\n null, options, options[0]);\n if (n == JOptionPane.YES_OPTION) {\n saveConfigPresets();\n // if the configChanged_ flag did not become false, the user \n // must have cancelled the configuration saving and we should cancel\n // quitting as well\n if (configChanged_) {\n return false;\n }\n }\n }\n if (liveModeTimer_ != null)\n liveModeTimer_.stop();\n \n // check needed to avoid deadlock\n if (!calledByImageJ) {\n if (!WindowManager.closeAllWindows()) {\n core_.logMessage(\"Failed to close some windows\");\n }\n }\n\n if (profileWin_ != null) {\n removeMMBackgroundListener(profileWin_);\n profileWin_.dispose();\n }\n\n if (scriptPanel_ != null) {\n removeMMBackgroundListener(scriptPanel_);\n scriptPanel_.closePanel();\n }\n\n if (pipelinePanel_ != null) {\n removeMMBackgroundListener(pipelinePanel_);\n pipelinePanel_.dispose();\n }\n\n if (propertyBrowser_ != null) {\n removeMMBackgroundListener(propertyBrowser_);\n propertyBrowser_.dispose();\n }\n\n if (acqControlWin_ != null) {\n removeMMBackgroundListener(acqControlWin_);\n acqControlWin_.close();\n }\n\n if (engine_ != null) {\n engine_.shutdown();\n }\n\n if (afMgr_ != null) {\n afMgr_.closeOptionsDialog();\n }\n\n engine_.disposeProcessors();\n\n pluginLoader_.disposePlugins();\n\n synchronized (shutdownLock_) {\n try {\n if (core_ != null) {\n ReportingUtils.setCore(null);\n core_.delete();\n core_ = null;\n }\n } catch (Exception err) {\n ReportingUtils.showError(err);\n }\n }\n return true;\n }\n\n private void saveSettings() {\n Rectangle r = this.getBounds();\n\n mainPrefs_.putInt(MAIN_FRAME_X, r.x);\n mainPrefs_.putInt(MAIN_FRAME_Y, r.y);\n mainPrefs_.putInt(MAIN_FRAME_WIDTH, r.width);\n mainPrefs_.putInt(MAIN_FRAME_HEIGHT, r.height);\n mainPrefs_.putInt(MAIN_FRAME_DIVIDER_POS, this.splitPane_.getDividerLocation());\n \n mainPrefs_.put(OPEN_ACQ_DIR, openAcqDirectory_);\n mainPrefs_.put(MAIN_SAVE_METHOD, \n ImageUtils.getImageStorageClass().getName());\n\n // save field values from the main window\n // NOTE: automatically restoring these values on startup may cause\n // problems\n mainPrefs_.put(MAIN_EXPOSURE, textFieldExp_.getText());\n\n // NOTE: do not save auto shutter state\n\n if (afMgr_ != null && afMgr_.getDevice() != null) {\n mainPrefs_.put(AUTOFOCUS_DEVICE, afMgr_.getDevice().getDeviceName());\n }\n }\n\n private void loadConfiguration() {\n File f = FileDialogs.openFile(this, \"Load a config file\",MM_CONFIG_FILE);\n if (f != null) {\n sysConfigFile_ = f.getAbsolutePath();\n configChanged_ = false;\n setConfigSaveButtonStatus(configChanged_);\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n loadSystemConfiguration();\n }\n }\n\n\n public synchronized boolean closeSequence(boolean calledByImageJ) {\n\n if (!this.isRunning()) {\n if (core_ != null) {\n core_.logMessage(\"MMStudioMainFrame::closeSequence called while running_ is false\");\n }\n return true;\n }\n \n if (engine_ != null && engine_.isAcquisitionRunning()) {\n int result = JOptionPane.showConfirmDialog(\n this,\n \"Acquisition in progress. Are you sure you want to exit and discard all data?\",\n \"Micro-Manager\", JOptionPane.YES_NO_OPTION,\n JOptionPane.INFORMATION_MESSAGE);\n\n if (result == JOptionPane.NO_OPTION) {\n return false;\n }\n }\n\n stopAllActivity();\n \n try {\n // Close all image windows associated with MM. Canceling saving of \n // any of these should abort shutdown\n if (!acqMgr_.closeAllImageWindows()) {\n return false;\n }\n } catch (MMScriptException ex) {\n // Not sure what to do here...\n }\n\n if (!cleanupOnClose(calledByImageJ)) {\n return false;\n }\n\n running_ = false;\n\n saveSettings();\n try {\n configPad_.saveSettings();\n options_.saveSettings();\n hotKeys_.saveSettings();\n } catch (NullPointerException e) {\n if (core_ != null)\n this.logError(e);\n } \n // disposing sometimes hangs ImageJ!\n // this.dispose();\n if (options_.closeOnExit_) {\n if (!runsAsPlugin_) {\n System.exit(0);\n } else {\n ImageJ ij = IJ.getInstance();\n if (ij != null) {\n ij.quit();\n }\n }\n } else {\n this.dispose();\n }\n \n return true;\n }\n\n /*\n public void applyContrastSettings(ContrastSettings contrast8,\n ContrastSettings contrast16) {\n ImagePlus img = WindowManager.getCurrentImage();\n if (img == null|| VirtualAcquisitionDisplay.getDisplay(img) == null )\n return;\n if (img.getBytesPerPixel() == 1) \n VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0,\n contrast8.min, contrast8.max, contrast8.gamma);\n else\n VirtualAcquisitionDisplay.getDisplay(img).setChannelContrast(0, \n contrast16.min, contrast16.max, contrast16.gamma);\n }\n */\n\n //TODO: Deprecated @Override\n public ContrastSettings getContrastSettings() {\n ImagePlus img = WindowManager.getCurrentImage();\n if (img == null || VirtualAcquisitionDisplay.getDisplay(img) == null )\n return null;\n return VirtualAcquisitionDisplay.getDisplay(img).getChannelContrastSettings(0);\n }\n \n/*\n public boolean is16bit() {\n ImagePlus ip = WindowManager.getCurrentImage();\n if (ip != null && ip.getProcessor() instanceof ShortProcessor) {\n return true;\n }\n return false;\n }\n * */\n\n public boolean isRunning() {\n return running_;\n }\n\n /**\n * Executes the beanShell script. This script instance only supports\n * commands directed to the core object.\n */\n private void executeStartupScript() {\n // execute startup script\n File f = new File(startupScriptFile_);\n\n if (startupScriptFile_.length() > 0 && f.exists()) {\n WaitDialog waitDlg = new WaitDialog(\n \"Executing startup script, please wait...\");\n waitDlg.showDialog();\n Interpreter interp = new Interpreter();\n try {\n // insert core object only\n interp.set(SCRIPT_CORE_OBJECT, core_);\n interp.set(SCRIPT_ACQENG_OBJECT, engine_);\n interp.set(SCRIPT_GUI_OBJECT, this);\n\n // read text file and evaluate\n interp.eval(TextUtils.readTextFile(startupScriptFile_));\n } catch (IOException exc) {\n ReportingUtils.logError(exc, \"Unable to read the startup script (\" + startupScriptFile_ + \").\");\n } catch (EvalError exc) {\n ReportingUtils.logError(exc);\n } finally {\n waitDlg.closeDialog();\n }\n } else {\n if (startupScriptFile_.length() > 0)\n ReportingUtils.logMessage(\"Startup script file (\"+startupScriptFile_+\") not present.\");\n }\n }\n\n /**\n * Loads system configuration from the cfg file.\n */\n private boolean loadSystemConfiguration() {\n boolean result = true;\n\n saveMRUConfigFiles();\n\n final WaitDialog waitDlg = new WaitDialog(\n \"Loading system configuration, please wait...\");\n\n waitDlg.setAlwaysOnTop(true);\n waitDlg.showDialog();\n this.setEnabled(false);\n\n try {\n if (sysConfigFile_.length() > 0) {\n GUIUtils.preventDisplayAdapterChangeExceptions();\n core_.waitForSystem();\n ignorePropertyChanges_ = true;\n core_.loadSystemConfiguration(sysConfigFile_);\n ignorePropertyChanges_ = false;\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n }\n } catch (final Exception err) {\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n ReportingUtils.showError(err);\n result = false;\n } finally {\n waitDlg.closeDialog();\n }\n setEnabled(true);\n initializeGUI();\n\n updateSwitchConfigurationMenu();\n\n FileDialogs.storePath(MM_CONFIG_FILE, new File(sysConfigFile_));\n\n return result;\n }\n\n private void saveMRUConfigFiles() {\n if (0 < sysConfigFile_.length()) {\n if (MRUConfigFiles_.contains(sysConfigFile_)) {\n MRUConfigFiles_.remove(sysConfigFile_);\n }\n if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {\n MRUConfigFiles_.remove(maxMRUCfgs_ - 1);\n }\n MRUConfigFiles_.add(0, sysConfigFile_);\n // save the MRU list to the preferences\n for (Integer icfg = 0; icfg < MRUConfigFiles_.size(); ++icfg) {\n String value = \"\";\n if (null != MRUConfigFiles_.get(icfg)) {\n value = MRUConfigFiles_.get(icfg).toString();\n }\n mainPrefs_.put(CFGFILE_ENTRY_BASE + icfg.toString(), value);\n }\n }\n }\n\n private void loadMRUConfigFiles() {\n sysConfigFile_ = mainPrefs_.get(SYSTEM_CONFIG_FILE, sysConfigFile_);\n // startupScriptFile_ = mainPrefs_.get(STARTUP_SCRIPT_FILE,\n // startupScriptFile_);\n MRUConfigFiles_ = new ArrayList();\n for (Integer icfg = 0; icfg < maxMRUCfgs_; ++icfg) {\n String value = \"\";\n value = mainPrefs_.get(CFGFILE_ENTRY_BASE + icfg.toString(), value);\n if (0 < value.length()) {\n File ruFile = new File(value);\n if (ruFile.exists()) {\n if (!MRUConfigFiles_.contains(value)) {\n MRUConfigFiles_.add(value);\n }\n }\n }\n }\n // initialize MRU list from old persistant data containing only SYSTEM_CONFIG_FILE\n if (0 < sysConfigFile_.length()) {\n if (!MRUConfigFiles_.contains(sysConfigFile_)) {\n // in case persistant data is inconsistent\n if (maxMRUCfgs_ <= MRUConfigFiles_.size()) {\n MRUConfigFiles_.remove(maxMRUCfgs_ - 1);\n }\n MRUConfigFiles_.add(0, sysConfigFile_);\n }\n }\n }\n\n /**\n * Opens Acquisition dialog.\n */\n private void openAcqControlDialog() {\n try {\n if (acqControlWin_ == null) {\n acqControlWin_ = new AcqControlDlg(engine_, mainPrefs_, this, options_);\n }\n if (acqControlWin_.isActive()) {\n acqControlWin_.setTopPosition();\n }\n\n acqControlWin_.setVisible(true);\n \n acqControlWin_.repaint();\n\n } catch (Exception exc) {\n ReportingUtils.showError(exc,\n \"\\nAcquistion window failed to open due to invalid or corrupted settings.\\n\"\n + \"Try resetting registry settings to factory defaults (Menu Tools|Options).\");\n }\n }\n \n\n private void updateChannelCombos() {\n if (this.acqControlWin_ != null) {\n this.acqControlWin_.updateChannelAndGroupCombo();\n }\n }\n \n private void runHardwareWizard() {\n try {\n if (configChanged_) {\n Object[] options = {\"Yes\", \"No\"};\n int n = JOptionPane.showOptionDialog(null,\n \"Save Changed Configuration?\", \"Micro-Manager\",\n JOptionPane.YES_NO_OPTION,\n JOptionPane.QUESTION_MESSAGE, null, options,\n options[0]);\n if (n == JOptionPane.YES_OPTION) {\n saveConfigPresets();\n }\n configChanged_ = false;\n }\n\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n\n // unload all devices before starting configurator\n core_.reset();\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n // run Configurator\n ConfiguratorDlg2 cfg2 = null;\n try {\n setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));\n cfg2 = new ConfiguratorDlg2(core_, sysConfigFile_);\n } finally {\n setCursor(Cursor.getDefaultCursor()); \t\t \n }\n\n if (cfg2 == null)\n {\n ReportingUtils.showError(\"Failed to launch Hardware Configuration Wizard\");\n return;\n }\n cfg2.setVisible(true);\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n // re-initialize the system with the new configuration file\n sysConfigFile_ = cfg2.getFileName();\n\n mainPrefs_.put(SYSTEM_CONFIG_FILE, sysConfigFile_);\n loadSystemConfiguration();\n GUIUtils.preventDisplayAdapterChangeExceptions();\n\n if (liveRunning) {\n enableLiveMode(liveRunning);\n }\n\n } catch (Exception e) {\n ReportingUtils.showError(e);\n }\n }\n\n private void autofocusNow() {\n if (afMgr_.getDevice() != null) {\n new Thread() {\n\n @Override\n public void run() {\n try {\n boolean lmo = isLiveModeOn();\n if (lmo) {\n enableLiveMode(false);\n }\n afMgr_.getDevice().fullFocus();\n if (lmo) {\n enableLiveMode(true);\n }\n } catch (MMException ex) {\n ReportingUtils.logError(ex);\n }\n }\n }.start(); // or any other method from Autofocus.java API\n }\n }\n \n\n private class ExecuteAcq implements Runnable {\n\n public ExecuteAcq() {\n }\n\n @Override\n public void run() {\n if (acqControlWin_ != null) {\n acqControlWin_.runAcquisition();\n }\n }\n }\n\n private void testForAbortRequests() throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n }\n }\n\n \n \n // //////////////////////////////////////////////////////////////////////////\n // Script interface\n // //////////////////////////////////////////////////////////////////////////\n\n @Override\n public String getVersion() {\n return MMVersion.VERSION_STRING;\n }\n \n /**\n * Inserts version info for various components in the Corelog\n */\n @Override\n public void logStartupProperties() {\n core_.logMessage(\"MM Studio version: \" + getVersion());\n core_.logMessage(core_.getVersionInfo());\n core_.logMessage(core_.getAPIVersionInfo());\n core_.logMessage(\"Operating System: \" + System.getProperty(\"os.name\") +\n \" (\" + System.getProperty(\"os.arch\") + \") \" + System.getProperty(\"os.version\"));\n core_.logMessage(\"JVM: \" + System.getProperty(\"java.vm.name\") +\n \", version \" + System.getProperty(\"java.version\") + \", \" +\n System.getProperty(\"sun.arch.data.model\") + \"-bit\");\n }\n \n @Override\n public void makeActive() {\n toFront();\n }\n \n \n @Override\n public boolean displayImage(TaggedImage ti) {\n normalizeTags(ti);\n return displayTaggedImage(ti, true);\n }\n \n /**\n * Opens a dialog to record stage positions\n */\n @Override\n public void showXYPositionList() {\n checkPosListDlg();\n posListDlg_.setVisible(true);\n }\n\n \n @Override\n public void setConfigChanged(boolean status) {\n configChanged_ = status;\n setConfigSaveButtonStatus(configChanged_);\n }\n \n /**\n * Lets JComponents register themselves so that their background can be\n * manipulated\n */\n @Override\n public void addMMBackgroundListener(Component comp) {\n if (MMFrames_.contains(comp))\n return;\n MMFrames_.add(comp);\n }\n\n /**\n * Lets JComponents remove themselves from the list whose background gets\n * changes\n */\n @Override\n public void removeMMBackgroundListener(Component comp) {\n if (!MMFrames_.contains(comp))\n return;\n MMFrames_.remove(comp);\n }\n\n\n /**\n * Returns exposure time for the desired preset in the given channelgroup\n * Acquires its info from the preferences\n * Same thing is used in MDA window, but this class keeps its own copy\n * \n * @param channelGroup\n * @param channel - \n * @param defaultExp - default value\n * @return exposure time\n */\n @Override\n public double getChannelExposureTime(String channelGroup, String channel,\n double defaultExp) {\n return exposurePrefs_.getDouble(\"Exposure_\" + channelGroup\n + \"_\" + channel, defaultExp);\n }\n\n /**\n * Updates the exposure time in the given preset \n * Will also update current exposure if it the given channel and channelgroup\n * are the current one\n * \n * @param channelGroup - \n * \n * @param channel - preset for which to change exposure time\n * @param exposure - desired exposure time\n */\n @Override\n public void setChannelExposureTime(String channelGroup, String channel,\n double exposure) {\n try {\n exposurePrefs_.putDouble(\"Exposure_\" + channelGroup + \"_\"\n + channel, exposure);\n if (channelGroup != null && channelGroup.equals(core_.getChannelGroup())) {\n if (channel != null && !channel.equals(\"\") && \n channel.equals(core_.getCurrentConfigFromCache(channelGroup))) {\n textFieldExp_.setText(NumberUtils.doubleToDisplayString(exposure));\n setExposure();\n }\n }\n } catch (Exception ex) {\n ReportingUtils.logError(\"Failed to set Exposure prefs using Channelgroup: \"\n + channelGroup + \", channel: \" + channel + \", exposure: \" + exposure);\n }\n }\n \n @Override\n public void enableRoiButtons(final boolean enabled) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n setRoiButton_.setEnabled(enabled);\n clearRoiButton_.setEnabled(enabled);\n }\n });\n }\n\n @Override\n public boolean getAutoreloadOption() {\n return options_.autoreloadDevices_;\n }\n\n /**\n * Returns the current background color\n * @return current background color\n */\n @Override\n public Color getBackgroundColor() {\n return guiColors_.background.get((options_.displayBackground_));\n }\n\n /*\n * Changes background color of this window and all other MM windows\n */\n @Override\n public void setBackgroundStyle(String backgroundType) {\n setBackground(guiColors_.background.get((backgroundType)));\n paint(MMStudioMainFrame.this.getGraphics());\n \n // sets background of all registered Components\n for (Component comp:MMFrames_) {\n if (comp != null)\n comp.setBackground(guiColors_.background.get(backgroundType));\n }\n }\n\n @Override\n public String getBackgroundStyle() {\n return options_.displayBackground_;\n }\n\n \n @Override\n public ImageWindow getSnapLiveWin() {\n if (simpleDisplay_ == null) {\n return null;\n }\n return simpleDisplay_.getHyperImage().getWindow();\n }\n \n \n /**\n * @Deprecated - used to be in api/AcquisitionEngine\n */\n public void startAcquisition() throws MMScriptException {\n testForAbortRequests();\n SwingUtilities.invokeLater(new ExecuteAcq());\n }\n\n @Override\n public String runAcquisition() throws MMScriptException {\n if (SwingUtilities.isEventDispatchThread()) {\n throw new MMScriptException(\"Acquisition can not be run from this (EDT) thread\");\n }\n testForAbortRequests();\n if (acqControlWin_ != null) {\n String name = acqControlWin_.runAcquisition();\n try {\n while (acqControlWin_.isAcquisitionRunning()) {\n Thread.sleep(50);\n }\n } catch (InterruptedException e) {\n ReportingUtils.showError(e);\n }\n return name;\n } else {\n throw new MMScriptException(\n \"Acquisition setup window must be open for this command to work.\");\n }\n }\n\n @Override\n public String runAcquisition(String name, String root)\n throws MMScriptException {\n testForAbortRequests();\n if (acqControlWin_ != null) {\n String acqName = acqControlWin_.runAcquisition(name, root);\n try {\n while (acqControlWin_.isAcquisitionRunning()) {\n Thread.sleep(100);\n }\n // ensure that the acquisition has finished.\n // This does not seem to work, needs something better\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n boolean finished = false;\n while (!finished) {\n ImageCache imCache = acq.getImageCache();\n if (imCache != null) {\n if (imCache.isFinished()) {\n finished = true;\n } else {\n Thread.sleep(100);\n }\n }\n }\n\n } catch (InterruptedException e) {\n ReportingUtils.showError(e);\n }\n return acqName;\n } else {\n throw new MMScriptException(\n \"Acquisition setup window must be open for this command to work.\");\n }\n }\n\n /**\n * @Deprecated used to be part of api\n */\n public String runAcqusition(String name, String root) throws MMScriptException {\n return runAcquisition(name, root);\n }\n\n /**\n * Loads acquisition settings from file\n * @param path file containing previously saved acquisition settings\n * @throws MMScriptException \n */\n @Override\n public void loadAcquisition(String path) throws MMScriptException {\n testForAbortRequests();\n try {\n engine_.shutdown();\n\n // load protocol\n if (acqControlWin_ != null) {\n acqControlWin_.loadAcqSettingsFromFile(path);\n }\n } catch (Exception ex) {\n throw new MMScriptException(ex.getMessage());\n }\n\n }\n\n @Override\n public void setPositionList(PositionList pl) throws MMScriptException {\n testForAbortRequests();\n // use serialization to clone the PositionList object\n posList_ = pl; // PositionList.newInstance(pl);\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n if (posListDlg_ != null)\n posListDlg_.setPositionList(posList_);\n \n if (engine_ != null)\n engine_.setPositionList(posList_);\n \n if (acqControlWin_ != null)\n acqControlWin_.updateGUIContents();\n }\n });\n }\n\n @Override\n public PositionList getPositionList() throws MMScriptException {\n testForAbortRequests();\n // use serialization to clone the PositionList object\n return posList_; //PositionList.newInstance(posList_);\n }\n\n @Override\n public void sleep(long ms) throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n scriptPanel_.sleep(ms);\n }\n }\n\n @Override\n public String getUniqueAcquisitionName(String stub) {\n return acqMgr_.getUniqueAcquisitionName(stub);\n }\n \n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions) throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices,\n nrPositions, true, false);\n }\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices) throws MMScriptException {\n openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0);\n }\n \n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions, boolean show)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, nrPositions, show, false);\n }\n\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, boolean show)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, false);\n } \n\n @Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, int nrPositions, boolean show, boolean save)\n throws MMScriptException {\n acqMgr_.openAcquisition(name, rootDir, show, save);\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.setDimensions(nrFrames, nrChannels, nrSlices, nrPositions);\n }\n\n //@Override\n public void openAcquisition(String name, String rootDir, int nrFrames,\n int nrChannels, int nrSlices, boolean show, boolean virtual)\n throws MMScriptException {\n this.openAcquisition(name, rootDir, nrFrames, nrChannels, nrSlices, 0, show, virtual);\n }\n\n //@Override\n public String createAcquisition(JSONObject summaryMetadata, boolean diskCached) {\n return createAcquisition(summaryMetadata, diskCached, false);\n }\n \n @Override\n @Deprecated\n public String createAcquisition(JSONObject summaryMetadata, boolean diskCached, boolean displayOff) {\n return acqMgr_.createAcquisition(summaryMetadata, diskCached, engine_, displayOff);\n }\n \n //@Override\n public void initializeSimpleAcquisition(String name, int width, int height,\n int byteDepth, int bitDepth, int multiCamNumCh) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, multiCamNumCh);\n acq.initializeSimpleAcq();\n }\n \n @Override\n public void initializeAcquisition(String name, int width, int height, int byteDepth, int bitDepth) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n //number of multi-cam cameras is set to 1 here for backwards compatibility\n //might want to change this later\n acq.setImagePhysicalDimensions(width, height, byteDepth, bitDepth, 1);\n acq.initialize();\n }\n\n @Override\n public int getAcquisitionImageWidth(String acqName) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getWidth();\n }\n\n @Override\n public int getAcquisitionImageHeight(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getHeight();\n }\n\n @Override\n public int getAcquisitionImageBitDepth(String acqName) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getBitDepth();\n }\n \n @Override\n public int getAcquisitionImageByteDepth(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getByteDepth();\n }\n\n @Override public int getAcquisitionMultiCamNumChannels(String acqName) throws MMScriptException{\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n return acq.getMultiCameraNumChannels();\n }\n \n @Override\n public Boolean acquisitionExists(String name) {\n return acqMgr_.acquisitionExists(name);\n }\n\n @Override\n public void closeAcquisition(String name) throws MMScriptException {\n acqMgr_.closeAcquisition(name);\n }\n\n /**\n * @Deprecated use closeAcquisitionWindow instead\n * @Deprecated - used to be in api/AcquisitionEngine\n */\n public void closeAcquisitionImage5D(String acquisitionName) throws MMScriptException {\n acqMgr_.closeImageWindow(acquisitionName);\n }\n\n @Override\n public void closeAcquisitionWindow(String acquisitionName) throws MMScriptException {\n acqMgr_.closeImageWindow(acquisitionName);\n }\n\n /**\n * @Deprecated - used to be in api/AcquisitionEngine\n * Since Burst and normal acquisition are now carried out by the same engine,\n * loadBurstAcquistion simply calls loadAcquisition\n * t\n * @param path - path to file specifying acquisition settings\n */\n public void loadBurstAcquisition(String path) throws MMScriptException {\n this.loadAcquisition(path);\n }\n\n @Override\n public void refreshGUI() {\n updateGUI(true);\n }\n \n @Override\n public void refreshGUIFromCache() {\n updateGUI(true, true);\n }\n\n @Override\n public void setAcquisitionProperty(String acqName, String propertyName,\n String value) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n acq.setProperty(propertyName, value);\n }\n\n public void setAcquisitionSystemState(String acqName, JSONObject md) throws MMScriptException {\n// acqMgr_.getAcquisition(acqName).setSystemState(md);\n setAcquisitionSummary(acqName, md);\n }\n\n //@Override\n public void setAcquisitionSummary(String acqName, JSONObject md) throws MMScriptException {\n acqMgr_.getAcquisition(acqName).setSummaryProperties(md);\n }\n\n @Override\n public void setImageProperty(String acqName, int frame, int channel,\n int slice, String propName, String value) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(acqName);\n acq.setProperty(frame, channel, slice, propName, value);\n }\n\n\n @Override\n public String getCurrentAlbum() {\n return acqMgr_.getCurrentAlbum();\n }\n \n @Override\n public void enableLiveMode(boolean enable) {\n if (core_ == null) {\n return;\n }\n if (enable == isLiveModeOn()) {\n return;\n }\n if (enable) {\n try {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n updateButtonsForLiveMode(false);\n return;\n }\n if (liveModeTimer_ == null) {\n liveModeTimer_ = new LiveModeTimer();\n }\n liveModeTimer_.begin();\n callLiveModeListeners(enable);\n } catch (Exception e) {\n ReportingUtils.showError(e);\n liveModeTimer_.stop();\n callLiveModeListeners(false);\n updateButtonsForLiveMode(false);\n return;\n }\n } else {\n liveModeTimer_.stop();\n callLiveModeListeners(enable);\n }\n updateButtonsForLiveMode(enable);\n }\n\n public String createNewAlbum() {\n return acqMgr_.createNewAlbum();\n }\n\n public void appendImage(String name, TaggedImage taggedImg) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n int f = 1 + acq.getLastAcquiredFrame();\n try {\n MDUtils.setFrameIndex(taggedImg.tags, f);\n } catch (JSONException e) {\n throw new MMScriptException(\"Unable to set the frame index.\");\n }\n acq.insertTaggedImage(taggedImg, f, 0, 0);\n }\n\n @Override\n public void addToAlbum(TaggedImage taggedImg) throws MMScriptException {\n addToAlbum(taggedImg, null);\n }\n \n public void addToAlbum(TaggedImage taggedImg, JSONObject displaySettings) throws MMScriptException {\n normalizeTags(taggedImg);\n acqMgr_.addToAlbum(taggedImg,displaySettings);\n }\n\n public void addImage(String name, Object img, int frame, int channel,\n int slice) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n acq.insertImage(img, frame, channel, slice);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg) throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n if (!acq.isInitialized()) {\n JSONObject tags = taggedImg.tags;\n \n // initialize physical dimensions of the image\n try {\n int width = tags.getInt(MMTags.Image.WIDTH);\n int height = tags.getInt(MMTags.Image.HEIGHT);\n int byteDepth = MDUtils.getDepth(tags);\n int bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);\n initializeAcquisition(name, width, height, byteDepth, bitDepth);\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n }\n acq.insertImage(taggedImg);\n }\n \n @Override\n /**\n * The basic method for adding images to an existing data set.\n * If the acquisition was not previously initialized, it will attempt to initialize it from the available image data\n */\n public void addImageToAcquisition(String name,\n int frame,\n int channel,\n int slice,\n int position,\n TaggedImage taggedImg) throws MMScriptException {\n\n // TODO: complete the tag set and initialize the acquisition\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n\n int positions = acq.getPositions();\n \n // check position, for multi-position data set the number of declared positions should be at least 2\n if (acq.getPositions() <= 1 && position > 0) {\n throw new MMScriptException(\"The acquisition was open as a single position data set.\\n\"\n + \"Open acqusition with two or more positions in order to crate a multi-position data set.\");\n }\n\n // check position, for multi-position data set the number of declared positions should be at least 2\n if (acq.getChannels() <= channel) {\n throw new MMScriptException(\"This acquisition was opened with \" + acq.getChannels() + \" channels.\\n\"\n + \"The channel number must not exceed declared number of positions.\");\n }\n\n\n JSONObject tags = taggedImg.tags;\n\n // if the acquisition was not previously initialized, set physical dimensions of the image\n if (!acq.isInitialized()) {\n\n // automatically initialize physical dimensions of the image\n try {\n int width = tags.getInt(MMTags.Image.WIDTH);\n int height = tags.getInt(MMTags.Image.HEIGHT);\n int byteDepth = MDUtils.getDepth(tags);\n int bitDepth = byteDepth * 8;\n if (tags.has(MMTags.Image.BIT_DEPTH)) {\n bitDepth = tags.getInt(MMTags.Image.BIT_DEPTH);\n }\n initializeAcquisition(name, width, height, byteDepth, bitDepth);\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n }\n\n // create required coordinate tags\n try {\n tags.put(MMTags.Image.FRAME_INDEX, frame);\n tags.put(MMTags.Image.FRAME, frame);\n tags.put(MMTags.Image.CHANNEL_INDEX, channel);\n tags.put(MMTags.Image.SLICE_INDEX, slice);\n tags.put(MMTags.Image.POS_INDEX, position);\n\n if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) {\n // add default setting\n tags.put(MMTags.Summary.SLICES_FIRST, true);\n tags.put(MMTags.Summary.TIME_FIRST, false);\n }\n\n if (acq.getPositions() > 1) {\n // if no position name is defined we need to insert a default one\n if (tags.has(MMTags.Image.POS_NAME)) {\n tags.put(MMTags.Image.POS_NAME, \"Pos\" + position);\n }\n }\n\n // update frames if necessary\n if (acq.getFrames() <= frame) {\n acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1));\n }\n\n } catch (JSONException e) {\n throw new MMScriptException(e);\n }\n\n // System.out.println(\"Inserting frame: \" + frame + \", channel: \" + channel + \", slice: \" + slice + \", pos: \" + position);\n acq.insertImage(taggedImg);\n }\n\n @Override\n /**\n * A quick way to implicitly snap an image and add it to the data set. Works\n * in the same way as above.\n */\n public void snapAndAddImage(String name, int frame, int channel, int slice, int position) throws MMScriptException {\n TaggedImage ti;\n try {\n if (core_.isSequenceRunning()) {\n ti = core_.getLastTaggedImage();\n } else {\n core_.snapImage();\n ti = core_.getTaggedImage();\n }\n MDUtils.setChannelIndex(ti.tags, channel);\n MDUtils.setFrameIndex(ti.tags, frame);\n MDUtils.setSliceIndex(ti.tags, slice);\n\n MDUtils.setPositionIndex(ti.tags, position);\n\n MMAcquisition acq = acqMgr_.getAcquisition(name);\n if (!acq.isInitialized()) {\n long width = core_.getImageWidth();\n long height = core_.getImageHeight();\n long depth = core_.getBytesPerPixel();\n long bitDepth = core_.getImageBitDepth();\n int multiCamNumCh = (int) core_.getNumberOfCameraChannels();\n\n acq.setImagePhysicalDimensions((int) width, (int) height, (int) depth, (int) bitDepth, multiCamNumCh);\n acq.initialize();\n }\n\n if (acq.getPositions() > 1) {\n MDUtils.setPositionName(ti.tags, \"Pos\" + position);\n }\n\n addImageToAcquisition(name, frame, channel, slice, position, ti);\n } catch (Exception e) {\n throw new MMScriptException(e);\n }\n }\n\n //@Override\n public void addImage(String name, TaggedImage img, boolean updateDisplay) throws MMScriptException {\n acqMgr_.getAcquisition(name).insertImage(img, updateDisplay);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg,\n boolean updateDisplay,\n boolean waitForDisplay) throws MMScriptException {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, updateDisplay, waitForDisplay);\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel,\n int slice, int position) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel, \n int slice, int position, boolean updateDisplay) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n } \n }\n\n //@Override\n public void addImage(String name, TaggedImage taggedImg, int frame, int channel,\n int slice, int position, boolean updateDisplay, boolean waitForDisplay) throws MMScriptException {\n try {\n acqMgr_.getAcquisition(name).insertImage(taggedImg, frame, channel, slice, position, updateDisplay, waitForDisplay);\n } catch (JSONException ex) {\n ReportingUtils.showError(ex);\n }\n }\n\n /**\n * Closes all acquisitions\n */\n @Override\n public void closeAllAcquisitions() {\n acqMgr_.closeAll();\n }\n\n @Override\n public String[] getAcquisitionNames()\n {\n return acqMgr_.getAcqusitionNames();\n }\n \n @Override\n @Deprecated\n public MMAcquisition getAcquisition(String name) throws MMScriptException {\n return acqMgr_.getAcquisition(name);\n }\n \n @Override\n public ImageCache getAcquisitionImageCache(String acquisitionName) throws MMScriptException {\n return getAcquisition(acquisitionName).getImageCache();\n }\n\n private class ScriptConsoleMessage implements Runnable {\n\n String msg_;\n\n public ScriptConsoleMessage(String text) {\n msg_ = text;\n }\n\n @Override\n public void run() {\n if (scriptPanel_ != null)\n scriptPanel_.message(msg_);\n }\n }\n\n @Override\n public void message(String text) throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n\n SwingUtilities.invokeLater(new ScriptConsoleMessage(text));\n }\n }\n\n @Override\n public void clearMessageWindow() throws MMScriptException {\n if (scriptPanel_ != null) {\n if (scriptPanel_.stopRequestPending()) {\n throw new MMScriptException(\"Script interrupted by the user!\");\n }\n scriptPanel_.clearOutput();\n }\n }\n\n public void clearOutput() throws MMScriptException {\n clearMessageWindow();\n }\n\n public void clear() throws MMScriptException {\n clearMessageWindow();\n }\n\n @Override\n public void setChannelContrast(String title, int channel, int min, int max)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelContrast(channel, min, max);\n }\n\n @Override\n public void setChannelName(String title, int channel, String name)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelName(channel, name);\n\n }\n\n @Override\n public void setChannelColor(String title, int channel, Color color)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setChannelColor(channel, color.getRGB());\n }\n \n @Override\n public void setContrastBasedOnFrame(String title, int frame, int slice)\n throws MMScriptException {\n MMAcquisition acq = acqMgr_.getAcquisition(title);\n acq.setContrastBasedOnFrame(frame, slice);\n }\n\n @Override\n public void setStagePosition(double z) throws MMScriptException {\n try {\n core_.setPosition(core_.getFocusDevice(),z);\n core_.waitForDevice(core_.getFocusDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public void setRelativeStagePosition(double z) throws MMScriptException {\n try {\n core_.setRelativePosition(core_.getFocusDevice(), z);\n core_.waitForDevice(core_.getFocusDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n\n @Override\n public void setXYStagePosition(double x, double y) throws MMScriptException {\n try {\n core_.setXYPosition(core_.getXYStageDevice(), x, y);\n core_.waitForDevice(core_.getXYStageDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public void setRelativeXYStagePosition(double x, double y) throws MMScriptException {\n try {\n core_.setRelativeXYPosition(core_.getXYStageDevice(), x, y);\n core_.waitForDevice(core_.getXYStageDevice());\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public Point2D.Double getXYStagePosition() throws MMScriptException {\n String stage = core_.getXYStageDevice();\n if (stage.length() == 0) {\n throw new MMScriptException(\"XY Stage device is not available\");\n }\n\n double x[] = new double[1];\n double y[] = new double[1];\n try {\n core_.getXYPosition(stage, x, y);\n Point2D.Double pt = new Point2D.Double(x[0], y[0]);\n return pt;\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n }\n\n @Override\n public String getXYStageName() {\n return core_.getXYStageDevice();\n }\n\n @Override\n public void setXYOrigin(double x, double y) throws MMScriptException {\n String xyStage = core_.getXYStageDevice();\n try {\n core_.setAdapterOriginXY(xyStage, x, y);\n } catch (Exception e) {\n throw new MMScriptException(e);\n }\n }\n\n public AcquisitionWrapperEngine getAcquisitionEngine() {\n return engine_;\n }\n\n @Override\n public String installAutofocusPlugin(String className) {\n try {\n return installAutofocusPlugin(Class.forName(className));\n } catch (ClassNotFoundException e) {\n String msg = \"Internal error: AF manager not instantiated.\";\n ReportingUtils.logError(e, msg);\n return msg;\n }\n }\n\n public String installAutofocusPlugin(Class> autofocus) {\n String msg = autofocus.getSimpleName() + \" module loaded.\";\n if (afMgr_ != null) {\n afMgr_.setAFPluginClassName(autofocus.getSimpleName());\n try {\n afMgr_.refresh();\n } catch (MMException e) {\n msg = e.getMessage();\n ReportingUtils.logError(e);\n }\n } else {\n msg = \"Internal error: AF manager not instantiated.\";\n }\n return msg;\n }\n\n public CMMCore getCore() {\n return core_;\n }\n\n @Override\n public IAcquisitionEngine2010 getAcquisitionEngine2010() {\n try {\n acquisitionEngine2010LoadingThread_.join();\n if (acquisitionEngine2010_ == null) {\n acquisitionEngine2010_ = (IAcquisitionEngine2010) acquisitionEngine2010Class_.getConstructor(ScriptInterface.class).newInstance(this);\n }\n return acquisitionEngine2010_;\n } catch (Exception e) {\n ReportingUtils.logError(e);\n return null;\n }\n }\n \n @Override\n public void addImageProcessor(DataProcessor processor) {\n getAcquisitionEngine().addImageProcessor(processor);\n }\n\n @Override\n public void removeImageProcessor(DataProcessor processor) {\n getAcquisitionEngine().removeImageProcessor(processor);\n }\n\n @Override\n public ArrayList> getImageProcessorPipeline() {\n return getAcquisitionEngine().getImageProcessorPipeline();\n }\n\n public void registerProcessorClass(Class> processorClass, String name) {\n getAcquisitionEngine().registerProcessorClass(processorClass, name);\n }\n\n // NB will need @Override tags once these functions are exposed in the \n // ScriptInterface.\n @Override\n public void setImageProcessorPipeline(List> pipeline) {\n getAcquisitionEngine().setImageProcessorPipeline(pipeline);\n }\n\n @Override\n public void setPause(boolean state) {\n\t getAcquisitionEngine().setPause(state);\n }\n\n @Override\n public boolean isPaused() {\n\t return getAcquisitionEngine().isPaused();\n }\n \n @Override\n public void attachRunnable(int frame, int position, int channel, int slice, Runnable runnable) {\n\t getAcquisitionEngine().attachRunnable(frame, position, channel, slice, runnable);\n }\n\n @Override\n public void clearRunnables() {\n\t getAcquisitionEngine().clearRunnables();\n }\n \n @Override\n public SequenceSettings getAcquisitionSettings() {\n\t if (engine_ == null)\n\t\t return new SequenceSettings();\n\t return engine_.getSequenceSettings();\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public SequenceSettings getAcqusitionSettings() {\n return getAcquisitionSettings();\n }\n \n @Override\n public void setAcquisitionSettings(SequenceSettings ss) {\n if (engine_ == null)\n return;\n \n engine_.setSequenceSettings(ss);\n acqControlWin_.updateGUIContents();\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public void setAcqusitionSettings(SequenceSettings ss) {\n setAcquisitionSettings(ss);\n }\n \n @Override\n public String getAcquisitionPath() {\n\t if (engine_ == null)\n\t\t return null;\n\t return engine_.getImageCache().getDiskLocation();\n }\n \n @Override\n public void promptToSaveAcquisition(String name, boolean prompt) throws MMScriptException {\n getAcquisition(name).promptToSave(prompt);\n }\n\n // Deprecated; use correctly spelled version. (Used to be part of API.)\n public void promptToSaveAcqusition(String name, boolean prompt) throws MMScriptException {\n promptToSaveAcquisition(name, prompt);\n }\n\n @Override\n public void setROI(Rectangle r) throws MMScriptException {\n boolean liveRunning = false;\n if (isLiveModeOn()) {\n liveRunning = true;\n enableLiveMode(false);\n }\n try {\n core_.setROI(r.x, r.y, r.width, r.height);\n } catch (Exception e) {\n throw new MMScriptException(e.getMessage());\n }\n updateStaticInfo();\n if (liveRunning) {\n enableLiveMode(true);\n }\n\n }\n\n public void snapAndAddToImage5D() {\n if (core_.getCameraDevice().length() == 0) {\n ReportingUtils.showError(\"No camera configured\");\n return;\n }\n try {\n if (this.isLiveModeOn()) {\n copyFromLiveModeToAlbum(simpleDisplay_);\n } else {\n doSnap(true);\n }\n } catch (Exception ex) {\n ReportingUtils.logError(ex);\n }\n }\n\n public void setAcquisitionEngine(AcquisitionWrapperEngine eng) {\n engine_ = eng;\n }\n \n public void suspendLiveMode() {\n liveModeSuspended_ = isLiveModeOn();\n enableLiveMode(false);\n }\n\n public void resumeLiveMode() {\n if (liveModeSuspended_) {\n enableLiveMode(true);\n }\n }\n\n @Override\n public Autofocus getAutofocus() {\n return afMgr_.getDevice();\n }\n\n @Override\n public void showAutofocusDialog() {\n if (afMgr_.getDevice() != null) {\n afMgr_.showOptionsDialog();\n }\n }\n\n @Override\n public AutofocusManager getAutofocusManager() {\n return afMgr_;\n }\n\n public void selectConfigGroup(String groupName) {\n configPad_.setGroup(groupName);\n }\n\n public String regenerateDeviceList() {\n Cursor oldc = Cursor.getDefaultCursor();\n Cursor waitc = new Cursor(Cursor.WAIT_CURSOR);\n setCursor(waitc);\n StringBuffer resultFile = new StringBuffer();\n MicroscopeModel.generateDeviceListFile(resultFile, core_);\n //MicroscopeModel.generateDeviceListFile();\n setCursor(oldc);\n return resultFile.toString();\n }\n \n @Override\n public void setImageSavingFormat(Class imageSavingClass) throws MMScriptException {\n if (! (imageSavingClass.equals(TaggedImageStorageDiskDefault.class) || \n imageSavingClass.equals(TaggedImageStorageMultipageTiff.class))) {\n throw new MMScriptException(\"Unrecognized saving class\");\n }\n ImageUtils.setImageStorageClass(imageSavingClass);\n if (acqControlWin_ != null) {\n acqControlWin_.updateSavingTypeButtons();\n }\n }\n \n \n /**\n * Allows MMListeners to register themselves\n */\n @Override\n public void addMMListener(MMListenerInterface newL) {\n if (MMListeners_.contains(newL))\n return;\n MMListeners_.add(newL);\n }\n\n /**\n * Allows MMListeners to remove themselves\n */\n @Override\n public void removeMMListener(MMListenerInterface oldL) {\n if (!MMListeners_.contains(oldL))\n return;\n MMListeners_.remove(oldL);\n }\n\n @Override\n public void logMessage(String msg) {\n ReportingUtils.logMessage(msg);\n }\n\n @Override\n public void showMessage(String msg) {\n ReportingUtils.showMessage(msg);\n }\n\n @Override\n public void logError(Exception e, String msg) {\n ReportingUtils.logError(e, msg);\n }\n\n @Override\n public void logError(Exception e) {\n ReportingUtils.logError(e);\n }\n\n @Override\n public void logError(String msg) {\n ReportingUtils.logError(msg);\n }\n\n @Override\n public void showError(Exception e, String msg) {\n ReportingUtils.showError(e, msg);\n }\n\n @Override\n public void showError(Exception e) {\n ReportingUtils.showError(e);\n }\n\n @Override\n public void showError(String msg) {\n ReportingUtils.showError(msg);\n }\n \n}\n"},"message":{"kind":"string","value":"Fixed a bug causing ProcessorPlugins to not work when selected from a non-root menu item.\n\ngit-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@13304 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd\n"},"old_file":{"kind":"string","value":"mmstudio/src/org/micromanager/MMStudioMainFrame.java"},"subject":{"kind":"string","value":"Fixed a bug causing ProcessorPlugins to not work when selected from a non-root menu item."}}},{"rowIdx":145830,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"598f659accdbe6029d2facf2459aed6154696dad"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"DemigodsRPG/Demigods3"},"new_contents":{"kind":"string","value":"package com.legit2.Demigods;\r\n\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport java.util.HashMap;\r\nimport java.util.Map.Entry;\r\n\r\nimport org.bukkit.OfflinePlayer;\r\nimport org.bukkit.entity.Player;\r\n\r\nimport com.legit2.Demigods.Utilities.DCharUtil;\r\nimport com.legit2.Demigods.Utilities.DDataUtil;\r\nimport com.legit2.Demigods.Utilities.DObjUtil;\r\nimport com.legit2.Demigods.Utilities.DPlayerUtil;\r\nimport com.legit2.Demigods.Utilities.DUtil;\r\n\r\npublic class DDatabase\r\n{\r\n\t/*\r\n\t * initializeDatabase() : Loads the MySQL or SQLite database.\r\n\t */\r\n\tpublic static void initializeDatabase()\r\n\t{\r\n\t\t// Check if MySQL is enabled in the configuration and if so, attempts to connect.\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\"))\r\n\t\t{\r\n\t\t\tDMySQL.createConnection();\r\n\t\t\tDMySQL.initializeMySQL();\r\n\t\t\tloadAllData();\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * uninitializeDatabase() : Unloads the MySQL or SQLite database.\r\n\t */\r\n\tpublic static void uninitializeDatabase()\r\n\t{\r\n\t\tsaveAllData();\r\n\t\t\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\r\n\t\t\tDMySQL.uninitializeMySQL();\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * addPlayerToDB() : Adds the player to the database.\r\n\t */\r\n\tpublic static void addPlayerToDB(OfflinePlayer player) throws SQLException\r\n\t{\r\n\t\t// Define variables\r\n\t\tLong firstLoginTime = System.currentTimeMillis();\r\n\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\tString playerName = player.getName();\r\n\t\t\t\r\n\t\t\tString addQuery = \"INSERT INTO \" + DMySQL.player_table + \" (player_id, player_name, player_characters, player_kills, player_deaths, player_firstlogin, player_lastlogin) VALUES (\" + playerID + \",'\" + playerName + \"', NULL, 0, 0,\" + firstLoginTime + \",\" + firstLoginTime +\");\";\r\n\t\t\tDMySQL.runQuery(addQuery);\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * removePlayerFromDB() : Removes the player from the database.\r\n\t */\r\n\tpublic static void removePlayerFromDB(OfflinePlayer player) throws SQLException\r\n\t{\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\t// TODO: Remove player from MySQL\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * addPlayerToDB() : Adds the player to the database.\r\n\t */\r\n\tpublic static void addCharToDB(OfflinePlayer player, int charID) throws SQLException\r\n\t{\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\tboolean charActive = DCharUtil.isActive(charID);\r\n\t\t\tString charName = DCharUtil.getName(charID);\r\n\t\t\tString charDeity = DCharUtil.getDeity(charID);\r\n\t\t\tString charAlliance = DCharUtil.getAlliance(charID);\r\n\t\t\tboolean charImmortal = DCharUtil.getImmortal(charID);\r\n\t\t\tint charHP = DCharUtil.getHP(charID);\r\n\t\t\tfloat charExp = DCharUtil.getExp(charID);\r\n\t\t\tint charFavor = DCharUtil.getFavor(charID);\r\n\t\t\tint charDevotion = DCharUtil.getDevotion(charID);\r\n\t\t\tint charAscensions = DCharUtil.getAscensions(charID);\r\n\t\t\tdouble charLastX = 0.0;\r\n\t\t\tdouble charLastY = 0.0;\r\n\t\t\tdouble charLastZ = 0.0;\r\n\t\t\tString charLastW = \"\";\r\n\t\t\t\r\n\t\t\tString addQuery = \r\n\t\t\t\t\t\"INSERT INTO \" + DMySQL.character_table +\r\n\t\t\t\t\t\"(char_id,player_id,char_active,char_name,char_deity,char_alliance,char_immortal,char_hp,char_exp,char_favor,char_devotion,char_ascensions,char_lastX,char_lastY,char_lastZ,char_lastW)\" + \r\n\t\t\t\t\t\"VALUES (\" +\r\n\t\t\t\t\t\tcharID + \",\" +\r\n\t\t\t\t\t\tplayerID + \",\" +\r\n\t\t\t\t\t\tcharActive + \",\" +\r\n\t\t\t\t\t\t\"'\" + charName + \"',\" +\r\n\t\t\t\t\t\t\"'\" + charDeity + \"',\" +\r\n\t\t\t\t\t\t\"'\" + charAlliance + \"',\" +\r\n\t\t\t\t\t\tcharImmortal + \",\" +\r\n\t\t\t\t\t\tcharHP + \",\" +\r\n\t\t\t\t\t\tcharExp + \",\" +\r\n\t\t\t\t\t\tcharFavor + \",\" +\r\n\t\t\t\t\t\tcharDevotion + \",\" +\r\n\t\t\t\t\t\tcharAscensions + \",\" +\r\n\t\t\t\t\t\tcharLastX + \",\" +\r\n\t\t\t\t\t\tcharLastY + \",\" +\r\n\t\t\t\t\t\tcharLastZ + \",\" +\r\n\t\t\t\t\t\t\"'\" + charLastW + \"'\" +\r\n\t\t\t\t\t\");\";\r\n\t\t\t\r\n\t\t\tDMySQL.runQuery(addQuery);\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * getPlayerInfo() : Grabs the player info from MySQL/FlatFile and returns (ResultSet)result.\r\n\t */\r\n\tpublic static ResultSet getPlayerInfo(String username) throws SQLException\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\r\n\t\t\t// TODO: Return player info from MySQL\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/*\r\n\t * loadAllData() : Loads all data from database into HashMaps.\r\n\t */\r\n\tpublic static void loadAllData()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tDUtil.info(\"Loading Demigods data...\");\r\n\r\n\t\t\t// Define variables\r\n\t\t\tint playerCount = 0;\r\n\t\t\tint characterCount = 0;\r\n\t\t\tlong startStopwatch = System.currentTimeMillis();\r\n\r\n\t\t\t// Define SELECT queries\r\n\t\t\tString selectPlayer = \"SELECT * FROM \" + DMySQL.player_table + \" LEFT JOIN \" + DMySQL.playerdata_table + \" ON \" + DMySQL.player_table + \".player_id = \" + DMySQL.playerdata_table + \".player_id;\";\r\n\t\t\tResultSet playerResult = DMySQL.runQuery(selectPlayer);\r\n\t\t\t\r\n\t\t\ttry \r\n\t\t\t{\r\n\t\t\t\twhile(playerResult.next())\r\n\t\t\t\t{\r\n\t\t\t\t\tplayerCount++;\r\n\t\t\t\t\t\r\n\t\t\t\t\tOfflinePlayer player = DPlayerUtil.definePlayer(playerResult.getString(\"player_name\"));\r\n\t\t\t\t\tint playerID = playerResult.getInt(\"player_id\");\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Load the main player data\r\n\t\t\t\t\tDDataUtil.addPlayer(player, playerID);\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_id\", playerResult.getInt(\"player_id\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_characters\", playerResult.getString(\"player_characters\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_kills\", playerResult.getInt(\"player_kills\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_deaths\", playerResult.getInt(\"player_deaths\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_firstlogin\", playerResult.getLong(\"player_firstlogin\"));\r\n\t\t\t\t\r\n\t\t\t\t\t// Load other player data\r\n\t\t\t\t\tif(playerResult.getString(\"datakey\") != null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(playerResult.getString(\"datakey\").contains(\"boolean_\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tDDataUtil.savePlayerData(player, playerResult.getString(\"datakey\"), playerResult.getBoolean(\"datavalue\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tDDataUtil.savePlayerData(player, playerResult.getString(\"datakey\"), playerResult.getString(\"datavalue\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\tString selectCharacter = \"SELECT * FROM \" + DMySQL.character_table + \" LEFT JOIN \" + DMySQL.chardata_table + \" ON \" + DMySQL.character_table + \".char_id = \" + DMySQL.chardata_table + \".char_id AND \" + DMySQL.character_table + \".player_id=\" + playerID + \";\";\r\n\t\t\t\t\tResultSet charResult = DMySQL.runQuery(selectCharacter);\r\n\r\n\r\n\t\t\t\t\twhile(charResult.next())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcharacterCount++;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tint charID = charResult.getInt(\"char_id\");\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Load the main character data\r\n\t\t\t\t\t\tDDataUtil.addChar(charID);\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_owner\", charResult.getString(\"player_id\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_name\", charResult.getString(\"char_name\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_active\", charResult.getString(\"char_active\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_deity\", charResult.getString(\"char_deity\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_alliance\", charResult.getString(\"char_alliance\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_immortal\", charResult.getBoolean(\"char_immortal\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_hp\", charResult.getInt(\"char_hp\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_exp\", charResult.getInt(\"char_exp\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastX\", charResult.getDouble(\"char_lastX\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastY\", charResult.getDouble(\"char_lastY\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastZ\", charResult.getDouble(\"char_lastZ\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastW\", charResult.getString(\"char_lastW\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_favor\", charResult.getInt(\"char_favor\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_devotion\", charResult.getInt(\"char_devotion\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_ascensions\", charResult.getInt(\"char_ascensions\"));\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Load other character data\r\n\t\t\t\t\t\tif(charResult.getString(\"datakey\") != null)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif(charResult.getString(\"datakey\").contains(\"boolean_\"))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDDataUtil.saveCharData(charID, charResult.getString(\"datakey\"), charResult.getBoolean(\"datavalue\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDDataUtil.saveCharData(charID, charResult.getString(\"datakey\"), charResult.getString(\"datavalue\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch(SQLException e)\r\n\t\t\t{\r\n\t\t\t\t// There was an error with the SQL.\r\n\t\t\t\tDUtil.severe(\"Error while loading Demigods data. (ERR: 1001)\");\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Stop the timer\r\n\t\t\tlong stopStopwatch = System.currentTimeMillis();\r\n\t\t\tdouble totalTime = (double) (stopStopwatch - startStopwatch);\r\n\t\t\t\r\n\t\t\t// Send data load success message\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Loaded data for \" + playerCount + \" players and \" + characterCount + \" characters in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Loaded data for \" + playerCount + \" players and \" + characterCount + \" characters.\");\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * saveAllData() : Saves all HashMap data to database.\r\n\t */\r\n\tpublic static boolean saveAllData()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\t// Define variables\r\n\t\t\tint playerCount = 0;\r\n\t\t\tlong startTimer = System.currentTimeMillis();\r\n\t\t\t\r\n\t\t\t// Save plugin-specific data\r\n\t\t\tsavePlugin();\r\n\t\t\tlong stopTimer = System.currentTimeMillis();\r\n\t\t\tdouble totalTime = (double) (stopTimer - startTimer);\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Demigods plugin data saved in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Demigods plugin data saved.\");\r\n\t\t\t\t\t\r\n\t\t\tfor(Player player : DUtil.getOnlinePlayers())\r\n\t\t\t{\r\n\t\t\t\tif(savePlayer(player)) playerCount++;\r\n\t\t\t}\r\n\r\n\t\t\t// Stop the timer\r\n\t\t\tstopTimer = System.currentTimeMillis();\r\n\t\t\ttotalTime = (double) (stopTimer - startTimer);\r\n\r\n\t\t\t// Send save success message\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Success! Saved \" + playerCount + \" of \" + DMySQL.getRows(DMySQL.runQuery(\"SELECT * FROM \" + DMySQL.player_table + \";\")) + \" players in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Success! Saved \" + playerCount + \" of \" + DMySQL.getRows(DMySQL.runQuery(\"SELECT * FROM \" + DMySQL.player_table + \";\")) + \" players.\");\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * savePlayerData() : Saves all HashMap data for (OfflinePlayer)player to database.\r\n\t */\r\n\tpublic static boolean savePlayer(OfflinePlayer player)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\r\n\t\t\t// Clear tables first\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID);\r\n\r\n\t\t\t// Save their player-specific data\r\n\t\t\tHashMap allPlayerData = DDataUtil.getAllPlayerData(player);\t\t\t\t\r\n\t\t\r\n\t\t\t// Define player-specific variables\r\n\t\t\tString playerChars = (String) allPlayerData.get(\"player_characters\");\r\n\t\t\tint playerKills = DObjUtil.toInteger(allPlayerData.get(\"player_kills\"));\r\n\t\t\tint playerDeaths = DObjUtil.toInteger(allPlayerData.get(\"player_deaths\"));\r\n\t\t\tLong playerLastLogin = (Long) allPlayerData.get(\"player_lastlogin\");\r\n\t\t\t\r\n\t\t\t// Update main player table\r\n\t\t\tDMySQL.runQuery(\"UPDATE \" + DMySQL.player_table + \" SET player_characters='\" + playerChars + \"',player_kills=\" + playerKills + \",player_deaths=\" + playerDeaths + \",player_lastlogin=\" + playerLastLogin + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\t\r\n\t\t\t// Save miscellaneous player data\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tfor(Entry playerData : allPlayerData.entrySet()) if(!playerData.getKey().contains(\"player_\")) DMySQL.runQuery(\"INSERT INTO \" + DMySQL.playerdata_table + \" (player_id, datakey, datavalue) VALUES(\" + playerID + \",'\" + playerData.getKey() + \"','\" + playerData.getValue() + \"');\");\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t// Save their character-specific data now\r\n\t\t\tHashMap> playerCharData = DDataUtil.getAllPlayerChars(player);\r\n\t\t\tfor(Entry> playerChar : playerCharData.entrySet())\r\n\t\t\t{\r\n\t\t\t\t// Define character-specific variables\r\n\t\t\t\tint charID = playerChar.getKey();\r\n\t\t\t\tboolean charImmortal = DObjUtil.toBoolean(playerCharData.get(charID).get(\"char_immortal\"));\r\n\t\t\t\tint charHP = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_hp\"));\r\n\t\t\t\tfloat charExp = DObjUtil.toFloat(playerCharData.get(charID).get(\"char_exp\"));\r\n\t\t\t\tint charFavor = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_favor\"));\r\n\t\t\t\tint charDevotion = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_devotion\"));\r\n\t\t\t\tint charAscensions = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_ascensions\"));\r\n\t\t\t\tDouble charLastX = (Double) playerCharData.get(charID).get(\"char_lastx\");\r\n\t\t\t\tDouble charLastY = (Double) playerCharData.get(charID).get(\"char_lasty\");\r\n\t\t\t\tDouble charLastZ = (Double) playerCharData.get(charID).get(\"char_lastz\");\r\n\t\t\t\tString charLastW = (String) playerCharData.get(charID).get(\"char_lastw\");\r\n\t\t\t\t\r\n\t\t\t\t// Update main character table\r\n\t\t\t\tDMySQL.runQuery(\"UPDATE \" + DMySQL.character_table + \" SET char_immortal=\" + charImmortal + \",char_hp=\" + charHP + \",char_exp=\" + charExp + \",char_favor=\" + charFavor + \",char_devotion=\" + charDevotion + \",char_ascensions=\" + charAscensions + \",char_lastX=\" + charLastX + \",char_lastY=\" + charLastY + \",char_lastZ=\" + charLastZ + \",char_lastW='\" + charLastW + \"' WHERE char_id=\" + charID + \";\");\r\n\r\n\t\t\t\t// Save miscellaneous character data\r\n\t\t\t\tHashMap charData = playerChar.getValue();\r\n\t\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.chardata_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\t\tfor(Entry character : charData.entrySet()) if(!character.getKey().contains(\"char_\")) DMySQL.runQuery(\"INSERT INTO \" + DMySQL.chardata_table + \" (char_id, datakey, datavalue) VALUES(\" + charID + \",'\" + character.getKey() + \"','\" + character.getValue() + \"');\");\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * savePluginData() : Saves all HashMap data for the plugin to the database.\r\n\t */\r\n\tpublic static boolean savePlugin()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\t// Clear tables first\r\n\t\t\tDMySQL.runQuery(\"TRUNCATE TABLE \" + DMySQL.plugindata_table + \";\");\r\n\r\n\t\t\t// Save their player-specific data\r\n\t\t\tHashMap> allPluginData = DDataUtil.getAllPluginData();\t\t\t\t\r\n\r\n\t\t\t// Save data\r\n\t\t\tfor(Entry> pluginData : allPluginData.entrySet())\r\n\t\t\t{\r\n\t\t\t\tString dataID = pluginData.getKey();\r\n\t\t\t\t\r\n\t\t\t\tfor(Entry data : pluginData.getValue().entrySet())\r\n\t\t\t\tif(!pluginData.getKey().contains(\"temp_\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tString dataKey = data.getKey();\r\n\t\t\t\t\tObject dataValue = data.getValue();\r\n\t\t\t\t\t\r\n\t\t\t\t\tDMySQL.runQuery(\"INSERT INTO \" + DMySQL.plugindata_table + \" (data_id, datakey, datavalue) VALUES('\" + dataID + \"','\" + dataKey + \"','\" + dataValue + \"');\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * removePlayer() : Removes the player completely from the database.\r\n\t */\r\n\tpublic static boolean removePlayer(OfflinePlayer player)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\t\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.player_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.character_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * removeChar() : Removes the character completely from the database.\r\n\t */\r\n\tpublic static boolean removeChar(int charID)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\t\t\t\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.character_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.chardata_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n}"},"new_file":{"kind":"string","value":"src/com/legit2/Demigods/DDatabase.java"},"old_contents":{"kind":"string","value":"package com.legit2.Demigods;\r\n\r\nimport java.sql.ResultSet;\r\nimport java.sql.SQLException;\r\nimport java.util.HashMap;\r\nimport java.util.Map.Entry;\r\n\r\nimport org.bukkit.OfflinePlayer;\r\nimport org.bukkit.entity.Player;\r\n\r\nimport com.legit2.Demigods.Utilities.DCharUtil;\r\nimport com.legit2.Demigods.Utilities.DDataUtil;\r\nimport com.legit2.Demigods.Utilities.DObjUtil;\r\nimport com.legit2.Demigods.Utilities.DPlayerUtil;\r\nimport com.legit2.Demigods.Utilities.DUtil;\r\n\r\npublic class DDatabase\r\n{\r\n\t/*\r\n\t * initializeDatabase() : Loads the MySQL or SQLite database.\r\n\t */\r\n\tpublic static void initializeDatabase()\r\n\t{\r\n\t\t// Check if MySQL is enabled in the configuration and if so, attempts to connect.\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\"))\r\n\t\t{\r\n\t\t\tDMySQL.createConnection();\r\n\t\t\tDMySQL.initializeMySQL();\r\n\t\t\tloadAllData();\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * uninitializeDatabase() : Unloads the MySQL or SQLite database.\r\n\t */\r\n\tpublic static void uninitializeDatabase()\r\n\t{\r\n\t\tsaveAllData();\r\n\t\t\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\r\n\t\t\tDMySQL.uninitializeMySQL();\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * addPlayerToDB() : Adds the player to the database.\r\n\t */\r\n\tpublic static void addPlayerToDB(OfflinePlayer player) throws SQLException\r\n\t{\r\n\t\t// Define variables\r\n\t\tLong firstLoginTime = System.currentTimeMillis();\r\n\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\tString playerName = player.getName();\r\n\t\t\t\r\n\t\t\tString addQuery = \"INSERT INTO \" + DMySQL.player_table + \" (player_id, player_name, player_characters, player_kills, player_deaths, player_firstlogin, player_lastlogin) VALUES (\" + playerID + \",'\" + playerName + \"', NULL, 0, 0,\" + firstLoginTime + \",\" + firstLoginTime +\");\";\r\n\t\t\tDMySQL.runQuery(addQuery);\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * removePlayerFromDB() : Removes the player from the database.\r\n\t */\r\n\tpublic static void removePlayerFromDB(OfflinePlayer player) throws SQLException\r\n\t{\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\t// TODO: Remove player from MySQL\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * addPlayerToDB() : Adds the player to the database.\r\n\t */\r\n\tpublic static void addCharToDB(OfflinePlayer player, int charID) throws SQLException\r\n\t{\r\n\t\t// Next we add them to the Database if needed\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\tboolean charActive = DCharUtil.isActive(charID);\r\n\t\t\tString charName = DCharUtil.getName(charID);\r\n\t\t\tString charDeity = DCharUtil.getDeity(charID);\r\n\t\t\tString charAlliance = DCharUtil.getAlliance(charID);\r\n\t\t\tboolean charImmortal = DCharUtil.getImmortal(charID);\r\n\t\t\tint charHP = DCharUtil.getHP(charID);\r\n\t\t\tfloat charExp = DCharUtil.getExp(charID);\r\n\t\t\tint charFavor = DCharUtil.getFavor(charID);\r\n\t\t\tint charDevotion = DCharUtil.getDevotion(charID);\r\n\t\t\tint charAscensions = DCharUtil.getAscensions(charID);\r\n\t\t\tdouble charLastX = 0.0;\r\n\t\t\tdouble charLastY = 0.0;\r\n\t\t\tdouble charLastZ = 0.0;\r\n\t\t\tString charLastW = \"\";\r\n\t\t\t\r\n\t\t\tString addQuery = \r\n\t\t\t\t\t\"INSERT INTO \" + DMySQL.character_table +\r\n\t\t\t\t\t\"(char_id,player_id,char_active,char_name,char_deity,char_alliance,char_immortal,char_hp,char_exp,char_favor,char_devotion,char_ascensions,char_lastX,char_lastY,char_lastZ,char_lastW)\" + \r\n\t\t\t\t\t\"VALUES (\" +\r\n\t\t\t\t\t\tcharID + \",\" +\r\n\t\t\t\t\t\tplayerID + \",\" +\r\n\t\t\t\t\t\tcharActive + \",\" +\r\n\t\t\t\t\t\t\"'\" + charName + \"',\" +\r\n\t\t\t\t\t\t\"'\" + charDeity + \"',\" +\r\n\t\t\t\t\t\t\"'\" + charAlliance + \"',\" +\r\n\t\t\t\t\t\tcharImmortal + \",\" +\r\n\t\t\t\t\t\tcharHP + \",\" +\r\n\t\t\t\t\t\tcharExp + \",\" +\r\n\t\t\t\t\t\tcharFavor + \",\" +\r\n\t\t\t\t\t\tcharDevotion + \",\" +\r\n\t\t\t\t\t\tcharAscensions + \",\" +\r\n\t\t\t\t\t\tcharLastX + \",\" +\r\n\t\t\t\t\t\tcharLastY + \",\" +\r\n\t\t\t\t\t\tcharLastZ + \",\" +\r\n\t\t\t\t\t\t\"'\" + charLastW + \"'\" +\r\n\t\t\t\t\t\");\";\r\n\t\t\t\r\n\t\t\tDMySQL.runQuery(addQuery);\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\t * getPlayerInfo() : Grabs the player info from MySQL/FlatFile and returns (ResultSet)result.\r\n\t */\r\n\tpublic static ResultSet getPlayerInfo(String username) throws SQLException\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\r\n\t\t\t// TODO: Return player info from MySQL\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t/*\r\n\t * loadAllData() : Loads all data from database into HashMaps.\r\n\t */\r\n\tpublic static void loadAllData()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\tDUtil.info(\"Loading Demigods data...\");\r\n\r\n\t\t\t// Define variables\r\n\t\t\tint playerCount = 0;\r\n\t\t\tint characterCount = 0;\r\n\t\t\tlong startStopwatch = System.currentTimeMillis();\r\n\r\n\t\t\t// Define SELECT queries\r\n\t\t\tString selectPlayer = \"SELECT * FROM \" + DMySQL.player_table + \" LEFT JOIN \" + DMySQL.playerdata_table + \" ON \" + DMySQL.player_table + \".player_id = \" + DMySQL.playerdata_table + \".player_id;\";\r\n\t\t\tResultSet playerResult = DMySQL.runQuery(selectPlayer);\r\n\t\t\t\r\n\t\t\ttry \r\n\t\t\t{\r\n\t\t\t\twhile(playerResult.next())\r\n\t\t\t\t{\r\n\t\t\t\t\tplayerCount++;\r\n\t\t\t\t\t\r\n\t\t\t\t\tOfflinePlayer player = DPlayerUtil.definePlayer(playerResult.getString(\"player_name\"));\r\n\t\t\t\t\tint playerID = playerResult.getInt(\"player_id\");\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Load the main player data\r\n\t\t\t\t\tDDataUtil.addPlayer(player, playerID);\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_id\", playerResult.getString(\"player_id\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_characters\", playerResult.getString(\"player_characters\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_kills\", playerResult.getInt(\"player_kills\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_deaths\", playerResult.getInt(\"player_deaths\"));\r\n\t\t\t\t\tDDataUtil.savePlayerData(player, \"player_firstlogin\", playerResult.getLong(\"player_firstlogin\"));\r\n\t\t\t\t\r\n\t\t\t\t\t// Load other player data\r\n\t\t\t\t\tif(playerResult.getString(\"datakey\") != null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(playerResult.getString(\"datakey\").contains(\"boolean_\"))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tDDataUtil.savePlayerData(player, playerResult.getString(\"datakey\"), playerResult.getBoolean(\"datavalue\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tDDataUtil.savePlayerData(player, playerResult.getString(\"datakey\"), playerResult.getString(\"datavalue\"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\tString selectCharacter = \"SELECT * FROM \" + DMySQL.character_table + \" LEFT JOIN \" + DMySQL.chardata_table + \" ON \" + DMySQL.character_table + \".char_id = \" + DMySQL.chardata_table + \".char_id AND \" + DMySQL.character_table + \".player_id=\" + playerID + \";\";\r\n\t\t\t\t\tResultSet charResult = DMySQL.runQuery(selectCharacter);\r\n\r\n\r\n\t\t\t\t\twhile(charResult.next())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcharacterCount++;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tint charID = charResult.getInt(\"char_id\");\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Load the main character data\r\n\t\t\t\t\t\tDDataUtil.addChar(charID);\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_owner\", charResult.getString(\"player_id\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_name\", charResult.getString(\"char_name\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_active\", charResult.getString(\"char_active\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_deity\", charResult.getString(\"char_deity\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_alliance\", charResult.getString(\"char_alliance\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_immortal\", charResult.getBoolean(\"char_immortal\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_hp\", charResult.getInt(\"char_hp\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_exp\", charResult.getInt(\"char_exp\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastX\", charResult.getDouble(\"char_lastX\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastY\", charResult.getDouble(\"char_lastY\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastZ\", charResult.getDouble(\"char_lastZ\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_lastW\", charResult.getString(\"char_lastW\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_favor\", charResult.getInt(\"char_favor\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_devotion\", charResult.getInt(\"char_devotion\"));\r\n\t\t\t\t\t\tDDataUtil.saveCharData(charID, \"char_ascensions\", charResult.getInt(\"char_ascensions\"));\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Load other character data\r\n\t\t\t\t\t\tif(charResult.getString(\"datakey\") != null)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif(charResult.getString(\"datakey\").contains(\"boolean_\"))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDDataUtil.saveCharData(charID, charResult.getString(\"datakey\"), charResult.getBoolean(\"datavalue\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tDDataUtil.saveCharData(charID, charResult.getString(\"datakey\"), charResult.getString(\"datavalue\"));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch(SQLException e)\r\n\t\t\t{\r\n\t\t\t\t// There was an error with the SQL.\r\n\t\t\t\tDUtil.severe(\"Error while loading Demigods data. (ERR: 1001)\");\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Stop the timer\r\n\t\t\tlong stopStopwatch = System.currentTimeMillis();\r\n\t\t\tdouble totalTime = (double) (stopStopwatch - startStopwatch);\r\n\t\t\t\r\n\t\t\t// Send data load success message\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Loaded data for \" + playerCount + \" players and \" + characterCount + \" characters in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Loaded data for \" + playerCount + \" players and \" + characterCount + \" characters.\");\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t}\r\n\t\r\n\t/*\r\n\t * saveAllData() : Saves all HashMap data to database.\r\n\t */\r\n\tpublic static boolean saveAllData()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\r\n\t\t\t// Define variables\r\n\t\t\tint playerCount = 0;\r\n\t\t\tlong startTimer = System.currentTimeMillis();\r\n\t\t\t\r\n\t\t\t// Save plugin-specific data\r\n\t\t\tsavePlugin();\r\n\t\t\tlong stopTimer = System.currentTimeMillis();\r\n\t\t\tdouble totalTime = (double) (stopTimer - startTimer);\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Demigods plugin data saved in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Demigods plugin data saved.\");\r\n\t\t\t\t\t\r\n\t\t\tfor(Player player : DUtil.getOnlinePlayers())\r\n\t\t\t{\r\n\t\t\t\tif(savePlayer(player)) playerCount++;\r\n\t\t\t}\r\n\r\n\t\t\t// Stop the timer\r\n\t\t\tstopTimer = System.currentTimeMillis();\r\n\t\t\ttotalTime = (double) (stopTimer - startTimer);\r\n\r\n\t\t\t// Send save success message\r\n\t\t\tif(DConfig.getSettingBoolean(\"data_debug\")) DUtil.info(\"Success! Saved \" + playerCount + \" of \" + DMySQL.getRows(DMySQL.runQuery(\"SELECT * FROM \" + DMySQL.player_table + \";\")) + \" players in \" + totalTime/1000 + \" seconds.\");\r\n\t\t\telse DUtil.info(\"Success! Saved \" + playerCount + \" of \" + DMySQL.getRows(DMySQL.runQuery(\"SELECT * FROM \" + DMySQL.player_table + \";\")) + \" players.\");\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * savePlayerData() : Saves all HashMap data for (OfflinePlayer)player to database.\r\n\t */\r\n\tpublic static boolean savePlayer(OfflinePlayer player)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\r\n\t\t\t// Clear tables first\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID);\r\n\r\n\t\t\t// Save their player-specific data\r\n\t\t\tHashMap allPlayerData = DDataUtil.getAllPlayerData(player);\t\t\t\t\r\n\t\t\r\n\t\t\t// Define player-specific variables\r\n\t\t\tString playerChars = (String) allPlayerData.get(\"player_characters\");\r\n\t\t\tint playerKills = DObjUtil.toInteger(allPlayerData.get(\"player_kills\"));\r\n\t\t\tint playerDeaths = DObjUtil.toInteger(allPlayerData.get(\"player_deaths\"));\r\n\t\t\tLong playerLastLogin = (Long) allPlayerData.get(\"player_lastlogin\");\r\n\t\t\t\r\n\t\t\t// Update main player table\r\n\t\t\tDMySQL.runQuery(\"UPDATE \" + DMySQL.player_table + \" SET player_characters='\" + playerChars + \"',player_kills=\" + playerKills + \",player_deaths=\" + playerDeaths + \",player_lastlogin=\" + playerLastLogin + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\t\r\n\t\t\t// Save miscellaneous player data\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tfor(Entry playerData : allPlayerData.entrySet()) if(!playerData.getKey().contains(\"player_\")) DMySQL.runQuery(\"INSERT INTO \" + DMySQL.playerdata_table + \" (player_id, datakey, datavalue) VALUES(\" + playerID + \",'\" + playerData.getKey() + \"','\" + playerData.getValue() + \"');\");\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t// Save their character-specific data now\r\n\t\t\tHashMap> playerCharData = DDataUtil.getAllPlayerChars(player);\r\n\t\t\tfor(Entry> playerChar : playerCharData.entrySet())\r\n\t\t\t{\r\n\t\t\t\t// Define character-specific variables\r\n\t\t\t\tint charID = playerChar.getKey();\r\n\t\t\t\tboolean charImmortal = DObjUtil.toBoolean(playerCharData.get(charID).get(\"char_immortal\"));\r\n\t\t\t\tint charHP = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_hp\"));\r\n\t\t\t\tfloat charExp = DObjUtil.toFloat(playerCharData.get(charID).get(\"char_exp\"));\r\n\t\t\t\tint charFavor = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_favor\"));\r\n\t\t\t\tint charDevotion = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_devotion\"));\r\n\t\t\t\tint charAscensions = DObjUtil.toInteger(playerCharData.get(charID).get(\"char_ascensions\"));\r\n\t\t\t\tDouble charLastX = (Double) playerCharData.get(charID).get(\"char_lastx\");\r\n\t\t\t\tDouble charLastY = (Double) playerCharData.get(charID).get(\"char_lasty\");\r\n\t\t\t\tDouble charLastZ = (Double) playerCharData.get(charID).get(\"char_lastz\");\r\n\t\t\t\tString charLastW = (String) playerCharData.get(charID).get(\"char_lastw\");\r\n\t\t\t\t\r\n\t\t\t\t// Update main character table\r\n\t\t\t\tDMySQL.runQuery(\"UPDATE \" + DMySQL.character_table + \" SET char_immortal=\" + charImmortal + \",char_hp=\" + charHP + \",char_exp=\" + charExp + \",char_favor=\" + charFavor + \",char_devotion=\" + charDevotion + \",char_ascensions=\" + charAscensions + \",char_lastX=\" + charLastX + \",char_lastY=\" + charLastY + \",char_lastZ=\" + charLastZ + \",char_lastW='\" + charLastW + \"' WHERE char_id=\" + charID + \";\");\r\n\r\n\t\t\t\t// Save miscellaneous character data\r\n\t\t\t\tHashMap charData = playerChar.getValue();\r\n\t\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.chardata_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\t\tfor(Entry character : charData.entrySet()) if(!character.getKey().contains(\"char_\")) DMySQL.runQuery(\"INSERT INTO \" + DMySQL.chardata_table + \" (char_id, datakey, datavalue) VALUES(\" + charID + \",'\" + character.getKey() + \"','\" + character.getValue() + \"');\");\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * savePluginData() : Saves all HashMap data for the plugin to the database.\r\n\t */\r\n\tpublic static boolean savePlugin()\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\t// Clear tables first\r\n\t\t\tDMySQL.runQuery(\"TRUNCATE TABLE \" + DMySQL.plugindata_table + \";\");\r\n\r\n\t\t\t// Save their player-specific data\r\n\t\t\tHashMap> allPluginData = DDataUtil.getAllPluginData();\t\t\t\t\r\n\r\n\t\t\t// Save data\r\n\t\t\tfor(Entry> pluginData : allPluginData.entrySet())\r\n\t\t\t{\r\n\t\t\t\tString dataID = pluginData.getKey();\r\n\t\t\t\t\r\n\t\t\t\tfor(Entry data : pluginData.getValue().entrySet())\r\n\t\t\t\tif(!pluginData.getKey().contains(\"temp_\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tString dataKey = data.getKey();\r\n\t\t\t\t\tObject dataValue = data.getValue();\r\n\t\t\t\t\t\r\n\t\t\t\t\tDMySQL.runQuery(\"INSERT INTO \" + DMySQL.plugindata_table + \" (data_id, datakey, datavalue) VALUES('\" + dataID + \"','\" + dataKey + \"','\" + dataValue + \"');\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * removePlayer() : Removes the player completely from the database.\r\n\t */\r\n\tpublic static boolean removePlayer(OfflinePlayer player)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\r\n\t\t\tint playerID = DPlayerUtil.getPlayerID(player);\r\n\t\t\t\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.player_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.playerdata_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.character_table + \" WHERE player_id=\" + playerID + \";\");\r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t/*\r\n\t * removeChar() : Removes the character completely from the database.\r\n\t */\r\n\tpublic static boolean removeChar(int charID)\r\n\t{\r\n\t\tif(DConfig.getSettingBoolean(\"mysql\") && DMySQL.checkConnection())\r\n\t\t{\t\t\t\t\t\t\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.character_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\tDMySQL.runQuery(\"DELETE FROM \" + DMySQL.chardata_table + \" WHERE char_id=\" + charID + \";\");\r\n\t\t\t\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(DConfig.getSettingBoolean(\"sqlite\"))\r\n\t\t{\r\n\t\t\t// TODO: SQLite\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n}"},"message":{"kind":"string","value":"ANOTHER BUG FIX."},"old_file":{"kind":"string","value":"src/com/legit2/Demigods/DDatabase.java"},"subject":{"kind":"string","value":"ANOTHER BUG FIX."}}},{"rowIdx":145831,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"38e51e409dbf7498d1f92c531d10c6a99061ba0e"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tripu/validator,takenspc/validator,tripu/validator,takenspc/validator,validator/validator,YOTOV-LIMITED/validator,validator/validator,YOTOV-LIMITED/validator,validator/validator,sammuelyee/validator,tripu/validator,sammuelyee/validator,YOTOV-LIMITED/validator,sammuelyee/validator,takenspc/validator,takenspc/validator,sammuelyee/validator,sammuelyee/validator,takenspc/validator,YOTOV-LIMITED/validator,validator/validator,validator/validator,tripu/validator,YOTOV-LIMITED/validator,tripu/validator"},"new_contents":{"kind":"string","value":"/*\n * Copyright (c) 2005 Henri Sivonen\n * Copyright (c) 2007-2012 Mozilla Foundation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a \n * copy of this software and associated documentation files (the \"Software\"), \n * to deal in the Software without restriction, including without limitation \n * the rights to use, copy, modify, merge, publish, distribute, sublicense, \n * and/or sell copies of the Software, and to permit persons to whom the \n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in \n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL \n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n * DEALINGS IN THE SOFTWARE.\n */\n\npackage nu.validator.servlet;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport nu.validator.messages.MessageEmitterAdapter;\nimport nu.validator.xml.PrudentHttpEntityResolver;\n\nimport org.apache.log4j.Logger;\n\n\n/**\n * @version $Id$\n * @author hsivonen\n */\npublic class VerifierServlet extends HttpServlet {\n /**\n * \n */\n private static final long serialVersionUID = 7811043632732680935L;\n\n private static final Logger log4j = Logger.getLogger(VerifierServlet.class);\n \n static final String GENERIC_HOST = System.getProperty(\"nu.validator.servlet.host.generic\", \"\");\n \n static final String HTML5_HOST = System.getProperty(\"nu.validator.servlet.host.html5\", \"\"); \n \n static final String PARSETREE_HOST = System.getProperty(\"nu.validator.servlet.host.parsetree\", \"\"); \n \n static final String GENERIC_PATH = System.getProperty(\"nu.validator.servlet.path.generic\", \"/\");\n \n static final String HTML5_PATH = System.getProperty(\"nu.validator.servlet.path.html5\", \"/html5/\"); \n \n static final String PARSETREE_PATH = System.getProperty(\"nu.validator.servlet.path.parsetree\", \"/parsetree/\"); \n \n static final boolean W3C_BRANDING = \"1\".equals(System.getProperty(\"nu.validator.servlet.w3cbranding\"));\n\n private static final byte[] GENERIC_ROBOTS_TXT;\n \n private static final byte[] HTML5_ROBOTS_TXT;\n\n private static final byte[] PARSETREE_ROBOTS_TXT;\n\n private static final byte[] STYLE_CSS;\n\n private static final byte[] SCRIPT_JS;\n\n private static final byte[] ICON_PNG;\n\n private static final byte[] W3C_PNG;\n\n private static final byte[] VNU_PNG;\n\n private static final byte[] HTML_PNG;\n\n private static final byte[] ABOUT_HTML;\n\n static {\n String aboutPath = System.getProperty(\n \"nu.validator.servlet.path.about\", \"./validator/site/\");\n try {\n GENERIC_ROBOTS_TXT = buildRobotsTxt(GENERIC_HOST, GENERIC_PATH, HTML5_HOST, HTML5_PATH, PARSETREE_HOST, PARSETREE_PATH);\n HTML5_ROBOTS_TXT = buildRobotsTxt(HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH, PARSETREE_HOST, PARSETREE_PATH);\n PARSETREE_ROBOTS_TXT = buildRobotsTxt(PARSETREE_HOST, PARSETREE_PATH, HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n try {\n STYLE_CSS = readFileFromPathIntoByteArray(aboutPath + \"style.css\");\n SCRIPT_JS = readFileFromPathIntoByteArray(aboutPath + \"script.js\");\n ICON_PNG = readFileFromPathIntoByteArray(aboutPath + \"icon.png\");\n if (W3C_BRANDING) {\n W3C_PNG = readFileFromPathIntoByteArray(aboutPath + \"w3c.png\");\n VNU_PNG = readFileFromPathIntoByteArray(aboutPath + \"vnu.png\");\n HTML_PNG = readFileFromPathIntoByteArray(aboutPath + \"html.png\");\n ABOUT_HTML = readFileFromPathIntoByteArray(aboutPath + \"about.html\");\n } else {\n W3C_PNG = VNU_PNG = HTML_PNG = ABOUT_HTML = null;\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n PrudentHttpEntityResolver.setParams(\n Integer.parseInt(System.getProperty(\"nu.validator.servlet.connection-timeout\",\"5000\")),\n Integer.parseInt(System.getProperty(\"nu.validator.servlet.socket-timeout\",\"5000\")),\n 100);\n PrudentHttpEntityResolver.setUserAgent(\"Validator.nu/LV\");\n // force some class loading\n new VerifierServletTransaction(null, null);\n new MessageEmitterAdapter(null, false, null, 0, null);\n }\n\n /**\n * @return\n * @throws UnsupportedEncodingException\n */\n private static byte[] buildRobotsTxt(String primaryHost, String primaryPath, String secondaryHost, String secondaryPath, String tertiaryHost, String tertiaryPath) throws UnsupportedEncodingException {\n StringBuilder builder = new StringBuilder();\n builder.append(\"User-agent: *\\nDisallow: \");\n builder.append(primaryPath);\n builder.append(\"?\\n\");\n if (primaryHost.equals(secondaryHost)) {\n builder.append(\"Disallow: \");\n builder.append(secondaryPath);\n builder.append(\"?\\n\"); \n }\n if (primaryHost.equals(tertiaryHost)) {\n builder.append(\"Disallow: \");\n builder.append(tertiaryPath);\n builder.append(\"?\\n\"); \n }\n return builder.toString().getBytes(\"UTF-8\");\n }\n \n private static byte[] readFileFromPathIntoByteArray(String path)\n throws IOException {\n File file = new File(path);\n byte[] buffer = new byte[(int) file.length()];\n InputStream ios = null;\n try {\n ios = new FileInputStream(file);\n if (ios.read(buffer) != buffer.length) {\n throw new IOException(\n \"Unexpected end of file reached while reading \" + path);\n }\n } finally {\n try {\n if (ios != null) {\n ios.close();\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return buffer;\n }\n\n private void writeResponse(byte[] buffer, String type,\n HttpServletResponse response) throws IOException {\n try {\n response.setContentType(type);\n response.setContentLength(buffer.length);\n response.setDateHeader(\"Expires\",\n System.currentTimeMillis() + 43200000); // 12 hours\n OutputStream out = response.getOutputStream();\n out.write(buffer);\n out.flush();\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return;\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n if (\"/robots.txt\".equals(request.getPathInfo())) {\n String serverName = request.getServerName();\n byte[] robotsTxt = null;\n if (hostMatch(GENERIC_HOST, serverName)) {\n robotsTxt = GENERIC_ROBOTS_TXT;\n } else if (hostMatch(HTML5_HOST, serverName)) {\n robotsTxt = HTML5_ROBOTS_TXT;\n } else if (hostMatch(PARSETREE_HOST, serverName)) {\n robotsTxt = PARSETREE_ROBOTS_TXT;\n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n writeResponse(robotsTxt, \"text/plain; charset=utf-8\", response);\n return;\n } else if (\"/style.css\".equals(request.getPathInfo())) {\n writeResponse(STYLE_CSS, \"text/css; charset=utf-8\", response);\n return;\n } else if (\"/script.js\".equals(request.getPathInfo())) {\n writeResponse(SCRIPT_JS, \"text/javascript; charset=utf-8\", response);\n return;\n } else if (\"/icon.png\".equals(request.getPathInfo())) {\n writeResponse(ICON_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/w3c.png\".equals(request.getPathInfo())) {\n writeResponse(W3C_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/vnu.png\".equals(request.getPathInfo())) {\n writeResponse(VNU_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/html.png\".equals(request.getPathInfo())) {\n writeResponse(HTML_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/about.html\".equals(request.getPathInfo())) {\n writeResponse(ABOUT_HTML, \"text/html; charset=utf-8\", response);\n return;\n }\n doPost(request, response);\n }\n\n private boolean hostMatch(String reference, String host) {\n if (\"\".equals(reference)) {\n return true;\n } else {\n // XXX case-sensitivity\n return reference.equalsIgnoreCase(host);\n }\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doOptions(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doOptions(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n String pathInfo = request.getPathInfo();\n if (\"*\".equals(pathInfo)) { // useless RFC 2616 complication\n return;\n } else if (\"/robots.txt\".equals(pathInfo)) {\n String serverName = request.getServerName();\n if (hostMatch(GENERIC_HOST, serverName)\n || hostMatch(HTML5_HOST, serverName)\n || hostMatch(PARSETREE_HOST, serverName)) {\n sendGetOnlyOptions(request, response);\n return;\n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n }\n doPost(request, response);\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,\n * javax.servlet.http.HttpServletResponse)\n */\n protected void doPost(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n String pathInfo = request.getPathInfo();\n if (pathInfo == null) {\n pathInfo = \"/\"; // Fix for Jigsaw\n }\n String serverName = request.getServerName();\n if (\"/robots.txt\".equals(pathInfo)) {\n // if we get here, we've got a POST\n response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\n return;\n }\n log4j.debug(\"pathInfo: \" + pathInfo);\n log4j.debug(\"serverName: \" + serverName);\n boolean isOptions = \"OPTIONS\".equals(request.getMethod());\n \n if (\"validator.nu\".equals(serverName) && \"/html5/\".equals(pathInfo)) {\n response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);\n String queryString = request.getQueryString();\n response.setHeader(\"Location\", \"http://html5.validator.nu/\" + (queryString == null ? \"\" : \"?\" + queryString));\n } else if (hostMatch(GENERIC_HOST, serverName) && GENERIC_PATH.equals(pathInfo)) {\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (isOptions) {\n response.setHeader(\"Access-Control-Policy-Path\", GENERIC_PATH);\n sendOptions(request, response);\n } else {\n new VerifierServletTransaction(request, response).service();\n } \n } else if (hostMatch(HTML5_HOST, serverName) && HTML5_PATH.equals(pathInfo)) {\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (isOptions) {\n sendOptions(request, response);\n } else {\n new Html5ConformanceCheckerTransaction(request, response).service();\n }\n } else if (hostMatch(PARSETREE_HOST, serverName) && PARSETREE_PATH.equals(pathInfo)) {\n if (isOptions) {\n sendGetOnlyOptions(request, response);\n } else {\n new ParseTreePrinter(request, response).service();\n } \n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n }\n }\n\n private void sendGetOnlyOptions(HttpServletRequest request, HttpServletResponse response) {\n response.setHeader(\"Allow\", \"GET, HEAD, OPTIONS\");\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, OPTIONS\");\n response.setContentType(\"application/octet-stream\");\n response.setContentLength(0);\n }\n\n private void sendOptions(HttpServletRequest request, HttpServletResponse response) {\n response.setHeader(\"Access-Control-Max-Age\", \"43200\"); // 12 hours\n response.setHeader(\"Allow\", \"GET, HEAD, POST, OPTIONS\");\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, OPTIONS\");\n response.setContentType(\"application/octet-stream\");\n response.setContentLength(0);\n }\n}\n"},"new_file":{"kind":"string","value":"src/nu/validator/servlet/VerifierServlet.java"},"old_contents":{"kind":"string","value":"/*\n * Copyright (c) 2005 Henri Sivonen\n * Copyright (c) 2007-2008 Mozilla Foundation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a \n * copy of this software and associated documentation files (the \"Software\"), \n * to deal in the Software without restriction, including without limitation \n * the rights to use, copy, modify, merge, publish, distribute, sublicense, \n * and/or sell copies of the Software, and to permit persons to whom the \n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in \n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR \n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL \n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING \n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \n * DEALINGS IN THE SOFTWARE.\n */\n\npackage nu.validator.servlet;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\n\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport nu.validator.messages.MessageEmitterAdapter;\nimport nu.validator.xml.PrudentHttpEntityResolver;\n\nimport org.apache.log4j.Logger;\n\n\n/**\n * @version $Id$\n * @author hsivonen\n */\npublic class VerifierServlet extends HttpServlet {\n /**\n * \n */\n private static final long serialVersionUID = 7811043632732680935L;\n\n private static final Logger log4j = Logger.getLogger(VerifierServlet.class);\n \n static final String GENERIC_HOST = System.getProperty(\"nu.validator.servlet.host.generic\", \"\");\n \n static final String HTML5_HOST = System.getProperty(\"nu.validator.servlet.host.html5\", \"\"); \n \n static final String PARSETREE_HOST = System.getProperty(\"nu.validator.servlet.host.parsetree\", \"\"); \n \n static final String GENERIC_PATH = System.getProperty(\"nu.validator.servlet.path.generic\", \"/\");\n \n static final String HTML5_PATH = System.getProperty(\"nu.validator.servlet.path.html5\", \"/html5/\"); \n \n static final String PARSETREE_PATH = System.getProperty(\"nu.validator.servlet.path.parsetree\", \"/parsetree/\"); \n \n static final boolean W3C_BRANDING = \"1\".equals(System.getProperty(\"nu.validator.servlet.w3cbranding\"));\n\n private static final byte[] GENERIC_ROBOTS_TXT;\n \n private static final byte[] HTML5_ROBOTS_TXT;\n\n private static final byte[] PARSETREE_ROBOTS_TXT;\n\n private static final byte[] STYLE_CSS;\n\n private static final byte[] SCRIPT_JS;\n\n private static final byte[] ICON_PNG;\n\n private static final byte[] W3C_PNG;\n\n private static final byte[] VNU_PNG;\n\n private static final byte[] HTML_PNG;\n\n private static final byte[] ABOUT_HTML;\n\n static {\n String aboutPath = System.getProperty(\n \"nu.validator.servlet.path.about\", \"./validator/site/\");\n try {\n GENERIC_ROBOTS_TXT = buildRobotsTxt(GENERIC_HOST, GENERIC_PATH, HTML5_HOST, HTML5_PATH, PARSETREE_HOST, PARSETREE_PATH);\n HTML5_ROBOTS_TXT = buildRobotsTxt(HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH, PARSETREE_HOST, PARSETREE_PATH);\n PARSETREE_ROBOTS_TXT = buildRobotsTxt(PARSETREE_HOST, PARSETREE_PATH, HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n try {\n STYLE_CSS = readFileFromPathIntoByteArray(aboutPath + \"style.css\");\n SCRIPT_JS = readFileFromPathIntoByteArray(aboutPath + \"script.js\");\n ICON_PNG = readFileFromPathIntoByteArray(aboutPath + \"icon.png\");\n if (W3C_BRANDING) {\n W3C_PNG = readFileFromPathIntoByteArray(aboutPath + \"w3c.png\");\n VNU_PNG = readFileFromPathIntoByteArray(aboutPath + \"vnu.png\");\n HTML_PNG = readFileFromPathIntoByteArray(aboutPath + \"html.png\");\n ABOUT_HTML = readFileFromPathIntoByteArray(aboutPath + \"about.html\");\n } else {\n W3C_PNG = VNU_PNG = HTML_PNG = ABOUT_HTML = null;\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n PrudentHttpEntityResolver.setParams(\n Integer.parseInt(System.getProperty(\"nu.validator.servlet.connection-timeout\",\"5000\")),\n Integer.parseInt(System.getProperty(\"nu.validator.servlet.socket-timeout\",\"5000\")),\n 100);\n PrudentHttpEntityResolver.setUserAgent(\"Validator.nu/LV\");\n // force some class loading\n new VerifierServletTransaction(null, null);\n new MessageEmitterAdapter(null, false, null, 0, null);\n }\n\n /**\n * @return\n * @throws UnsupportedEncodingException\n */\n private static byte[] buildRobotsTxt(String primaryHost, String primaryPath, String secondaryHost, String secondaryPath, String tertiaryHost, String tertiaryPath) throws UnsupportedEncodingException {\n StringBuilder builder = new StringBuilder();\n builder.append(\"User-agent: *\\nDisallow: \");\n builder.append(primaryPath);\n builder.append(\"?\\n\");\n if (primaryHost.equals(secondaryHost)) {\n builder.append(\"Disallow: \");\n builder.append(secondaryPath);\n builder.append(\"?\\n\"); \n }\n if (primaryHost.equals(tertiaryHost)) {\n builder.append(\"Disallow: \");\n builder.append(tertiaryPath);\n builder.append(\"?\\n\"); \n }\n return builder.toString().getBytes(\"UTF-8\");\n }\n \n private static byte[] readFileFromPathIntoByteArray(String path)\n throws IOException {\n File file = new File(path);\n byte[] buffer = new byte[(int) file.length()];\n InputStream ios = null;\n try {\n ios = new FileInputStream(file);\n if (ios.read(buffer) != buffer.length) {\n throw new IOException(\n \"Unexpected end of file reached while reading \" + path);\n }\n } finally {\n try {\n if (ios != null) {\n ios.close();\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return buffer;\n }\n\n private void writeResponse(byte[] buffer, String type,\n HttpServletResponse response) throws IOException {\n try {\n response.setContentType(type);\n response.setContentLength(buffer.length);\n response.setDateHeader(\"Expires\",\n System.currentTimeMillis() + 43200000); // 12 hours\n OutputStream out = response.getOutputStream();\n out.write(buffer);\n out.flush();\n out.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return;\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n if (\"/robots.txt\".equals(request.getPathInfo())) {\n String serverName = request.getServerName();\n byte[] robotsTxt = null;\n if (hostMatch(GENERIC_HOST, serverName)) {\n robotsTxt = GENERIC_ROBOTS_TXT;\n } else if (hostMatch(HTML5_HOST, serverName)) {\n robotsTxt = HTML5_ROBOTS_TXT;\n } else if (hostMatch(PARSETREE_HOST, serverName)) {\n robotsTxt = PARSETREE_ROBOTS_TXT;\n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n writeResponse(robotsTxt, \"text/plain; charset=utf-8\", response);\n return;\n } else if (\"/style.css\".equals(request.getPathInfo())) {\n writeResponse(STYLE_CSS, \"text/css; charset=utf-8\", response);\n return;\n } else if (\"/script.js\".equals(request.getPathInfo())) {\n writeResponse(SCRIPT_JS, \"text/javascript charset=utf-8\", response);\n return;\n } else if (\"/icon.png\".equals(request.getPathInfo())) {\n writeResponse(ICON_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/w3c.png\".equals(request.getPathInfo())) {\n writeResponse(W3C_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/vnu.png\".equals(request.getPathInfo())) {\n writeResponse(VNU_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/html.png\".equals(request.getPathInfo())) {\n writeResponse(HTML_PNG, \"image/png\", response);\n return;\n } else if (W3C_BRANDING && \"/about.html\".equals(request.getPathInfo())) {\n writeResponse(ABOUT_HTML, \"text/html; charset=utf-8\", response);\n return;\n }\n doPost(request, response);\n }\n\n private boolean hostMatch(String reference, String host) {\n if (\"\".equals(reference)) {\n return true;\n } else {\n // XXX case-sensitivity\n return reference.equalsIgnoreCase(host);\n }\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doOptions(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doOptions(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n String pathInfo = request.getPathInfo();\n if (\"*\".equals(pathInfo)) { // useless RFC 2616 complication\n return;\n } else if (\"/robots.txt\".equals(pathInfo)) {\n String serverName = request.getServerName();\n if (hostMatch(GENERIC_HOST, serverName)\n || hostMatch(HTML5_HOST, serverName)\n || hostMatch(PARSETREE_HOST, serverName)) {\n sendGetOnlyOptions(request, response);\n return;\n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n return;\n }\n }\n doPost(request, response);\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)\n */\n @Override\n protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\n }\n\n /**\n * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,\n * javax.servlet.http.HttpServletResponse)\n */\n protected void doPost(HttpServletRequest request,\n HttpServletResponse response) throws ServletException, IOException {\n String pathInfo = request.getPathInfo();\n if (pathInfo == null) {\n pathInfo = \"/\"; // Fix for Jigsaw\n }\n String serverName = request.getServerName();\n if (\"/robots.txt\".equals(pathInfo)) {\n // if we get here, we've got a POST\n response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);\n return;\n }\n log4j.debug(\"pathInfo: \" + pathInfo);\n log4j.debug(\"serverName: \" + serverName);\n boolean isOptions = \"OPTIONS\".equals(request.getMethod());\n \n if (\"validator.nu\".equals(serverName) && \"/html5/\".equals(pathInfo)) {\n response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);\n String queryString = request.getQueryString();\n response.setHeader(\"Location\", \"http://html5.validator.nu/\" + (queryString == null ? \"\" : \"?\" + queryString));\n } else if (hostMatch(GENERIC_HOST, serverName) && GENERIC_PATH.equals(pathInfo)) {\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (isOptions) {\n response.setHeader(\"Access-Control-Policy-Path\", GENERIC_PATH);\n sendOptions(request, response);\n } else {\n new VerifierServletTransaction(request, response).service();\n } \n } else if (hostMatch(HTML5_HOST, serverName) && HTML5_PATH.equals(pathInfo)) {\n response.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n if (isOptions) {\n sendOptions(request, response);\n } else {\n new Html5ConformanceCheckerTransaction(request, response).service();\n }\n } else if (hostMatch(PARSETREE_HOST, serverName) && PARSETREE_PATH.equals(pathInfo)) {\n if (isOptions) {\n sendGetOnlyOptions(request, response);\n } else {\n new ParseTreePrinter(request, response).service();\n } \n } else {\n response.sendError(HttpServletResponse.SC_NOT_FOUND);\n }\n }\n\n private void sendGetOnlyOptions(HttpServletRequest request, HttpServletResponse response) {\n response.setHeader(\"Allow\", \"GET, HEAD, OPTIONS\");\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, OPTIONS\");\n response.setContentType(\"application/octet-stream\");\n response.setContentLength(0);\n }\n\n private void sendOptions(HttpServletRequest request, HttpServletResponse response) {\n response.setHeader(\"Access-Control-Max-Age\", \"43200\"); // 12 hours\n response.setHeader(\"Allow\", \"GET, HEAD, POST, OPTIONS\");\n response.setHeader(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, OPTIONS\");\n response.setContentType(\"application/octet-stream\");\n response.setContentLength(0);\n }\n}\n"},"message":{"kind":"string","value":"Fixed typo and updated copyright date.\n"},"old_file":{"kind":"string","value":"src/nu/validator/servlet/VerifierServlet.java"},"subject":{"kind":"string","value":"Fixed typo and updated copyright date."}}},{"rowIdx":145832,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"7898f22db3b41754ee7ad97c29d79d32cb766fc0"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"frc2399/2015-code"},"new_contents":{"kind":"string","value":"package org.usfirst.frc.team2399.robot;\n\nimport org.usfirst.frc.team2399.robot.commands.DriveAutoZone;\n//import org.usfirst.frc.team2399.robot.OI;\nimport org.usfirst.frc.team2399.robot.subsystems.DriveTrain;\nimport org.usfirst.frc.team2399.robot.subsystems.Elevator;\n\nimport edu.wpi.first.wpilibj.DigitalInput;\nimport edu.wpi.first.wpilibj.Gyro;\nimport edu.wpi.first.wpilibj.IterativeRobot;\nimport edu.wpi.first.wpilibj.Joystick;\nimport edu.wpi.first.wpilibj.buttons.Button;\nimport edu.wpi.first.wpilibj.command.Command;\nimport edu.wpi.first.wpilibj.command.Scheduler;\nimport edu.wpi.first.wpilibj.command.Subsystem;\nimport edu.wpi.first.wpilibj.livewindow.LiveWindow;\nimport edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;\n\n/**\n * The VM is configured to automatically run this class, and to call the\n * functions corresponding to each mode, as described in the IterativeRobot\n * documentation. If you change the name of this class or the package after\n * creating this project, you must also update the manifest file in the resource\n * directory.\n */\n\n// THIS CLASS HAS REPLACED COMMANDBASE/COMMANDS\npublic class Robot extends IterativeRobot {\n\t// established static variables\n\n\tpublic static OI oi;\n\n\tpublic static DriveTrain driveTrain;\n//\tpublic static Button reduceSpeedButt;\n\n\tpublic static Elevator elevatorFront;\n\tpublic static Elevator elevatorRear;\n\n\tpublic static Joystick joystick;\n\n\t// established contact switches\n\n\tpublic static DigitalInput contactSwitchOne = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH1ID);\n\tpublic static DigitalInput contactSwitchTwo = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH2ID);\n\tpublic static DigitalInput contactSwitchThree = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH3ID);\n\tpublic static DigitalInput contactSwitchFour = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH4ID);\n\n\tprivate Command autoncommand;\n\n\t/**\n\t * This function is run when the robot is first started up and should be\n\t * used for any initialization code.\n\t */\n\n\t// if you want to take out an auton mode, comment out autoncommand = new\n\n\tpublic void robotInit() {\n\n\t\t// established new instances of drivetrain, elevator, OI and an\n\t\t// autonomus command\n\n\t\tdriveTrain = new DriveTrain();\n\n\t\televatorFront = new Elevator(RobotMap.ELEVATORFRONT_JAGUARID);\n\t\televatorRear = new Elevator(RobotMap.ELEVATORREAR_JAGUARID);\n\n\t\toi = new OI();\n\n\t\tautoncommand = new DriveAutoZone();\n\n\t\t// smartdashboard values for drivetrain and elevator\n\t\tSmartDashboard.putData(\"Drive Train\", driveTrain);\n\n\t\tSmartDashboard.putData(\"Front Elevator\", elevatorFront);\n\t\tSmartDashboard.putData(\"Rear Elevator\", elevatorRear);\n\n\t\t// instantiate the command used for the autonomous period\n\n\t}\n\n\t// established wait command for later use\n\tprivate void WaitCommmand(double d) {\n\n\t}\n\n\t// When Contact switches are pushed for at least 0.005 seconds, they will\n\t// show up as Pressed on SmartDashboard.\n\t\n//\tpublic void reduceSpeedButt() {\n//\t\tif (reduceSpeedButt.get() == true){\n//\t\t\tWaitCommmand(0.005);\n//\t\t\tx = .5 * x;\n//\t\t\ty = .5 * y;\n//\t\t\ttwist = .5 * twist;\n//\t\t\tdriveTrain.driveFieldOriented(x, y, twist);\n//\t\t}\n//\t}\n\n\t\n\t\n\tpublic void contactSwitchOne() {\n\t\tif (contactSwitchOne.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch One Pressed\",\n\t\t\t\t\tcontactSwitchOne.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchTwo() {\n\t\tif (contactSwitchTwo.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch Two Pressed\",\n\t\t\t\t\tcontactSwitchTwo.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchThree() {\n\t\tif (contactSwitchThree.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch Three Pressed\",\n\t\t\t\t\tcontactSwitchThree.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchFour() {\n\t\tif (contactSwitchFour.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Switch Four Pressed\",\n\t\t\t\t\tcontactSwitchFour.get());\n\t\t}\n\t}\n\n\t// made it so Contact Switches would return true when pressed\n\tprotected boolean contactSwitchOneReturnTrue() {\n\t\tif (contactSwitchOne.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchTwoReturnTrue() {\n\t\tif (contactSwitchTwo.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchThreeReturnTrue() {\n\t\tif (contactSwitchThree.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchFourReturnTrue() {\n\t\tif (contactSwitchFour.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// TODO figure out what this is so we can write a better comment\n\tpublic void disabledPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\t// schedule the autonomous command (example)\n\tpublic void autonomousInit() {\n\t\tif (autoncommand != null) {\n\t\t\tautoncommand.start();\n\t\t}\n\n\t}\n\n\t/**\n\t * This function is called periodically during autonomous\n\t */\n\tpublic void autonomousPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\tpublic void teleopInit() {\n\t\t// This makes sure that the autonomous stops running when\n\t\t// teleop starts running. If you want the autonomous to\n\t\t// continue until interrupted by another command, remove\n\t\t// this line or comment it out.\n\n\t}\n\n\t/**\n\t * This function is called when the disabled button is hit. You can use it\n\t * to reset subsystems before shutting down.\n\t */\n\tpublic void disabledInit() {\n\n\t}\n\n\t/**\n\t * This function is called periodically during operator control\n\t */\n\tpublic void teleopPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\t/**\n\t * This function is called periodically during test mode\n\t */\n\tpublic void testPeriodic() {\n\t\tLiveWindow.run();\n\t}\n}\n"},"new_file":{"kind":"string","value":"src/org/usfirst/frc/team2399/robot/Robot.java"},"old_contents":{"kind":"string","value":"package org.usfirst.frc.team2399.robot;\n\nimport org.usfirst.frc.team2399.robot.commands.DriveAutoZone;\n//import org.usfirst.frc.team2399.robot.OI;\nimport org.usfirst.frc.team2399.robot.subsystems.DriveTrain;\nimport org.usfirst.frc.team2399.robot.subsystems.Elevator;\n\nimport edu.wpi.first.wpilibj.DigitalInput;\nimport edu.wpi.first.wpilibj.Gyro;\nimport edu.wpi.first.wpilibj.IterativeRobot;\nimport edu.wpi.first.wpilibj.Joystick;\nimport edu.wpi.first.wpilibj.buttons.Button;\nimport edu.wpi.first.wpilibj.command.Command;\nimport edu.wpi.first.wpilibj.command.Scheduler;\nimport edu.wpi.first.wpilibj.command.Subsystem;\nimport edu.wpi.first.wpilibj.livewindow.LiveWindow;\nimport edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;\n\n/**\n * The VM is configured to automatically run this class, and to call the\n * functions corresponding to each mode, as described in the IterativeRobot\n * documentation. If you change the name of this class or the package after\n * creating this project, you must also update the manifest file in the resource\n * directory.\n */\n\n// THIS CLASS HAS REPLACED COMMANDBASE/COMMANDS\npublic class Robot extends IterativeRobot {\n\t// established static variables\n\n\tpublic static OI oi;\n\n\tpublic static DriveTrain driveTrain;\n//\tpublic static Button reduceSpeedButt;\n\n\tpublic static Elevator elevatorFront;\n\tpublic static Elevator elevatorRear;\n\n\tpublic static Joystick joystick;\n\n\t// established contact switches\n\n\tpublic static DigitalInput contactSwitchOne = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH1ID);\n\tpublic static DigitalInput contactSwitchTwo = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH2ID);\n\tpublic static DigitalInput contactSwitchThree = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH3ID);\n\tpublic static DigitalInput contactSwitchFour = new DigitalInput(\n\t\t\tRobotMap.CONTACT_SWITCH4ID);\n\n\tprivate Command autoncommand;\n\n\t/**\n\t * This function is run when the robot is first started up and should be\n\t * used for any initialization code.\n\t */\n\n\t// if you want to take out an auton mode, comment out autoncommand = new\n\n\tpublic void robotInit() {\n\n\t\t// established new instances of drivetrain, elevator, OI and an\n\t\t// autonomus command\n\n\t\tdriveTrain = new DriveTrain();\n\n\t\televatorFront = new Elevator(RobotMap.ELEVATORFRONT_JAGUARID);\n\t\televatorRear = new Elevator(RobotMap.ELEVATORREAR_JAGUARID);\n\n\t\toi = new OI();\n\n\t\tautoncommand = new DriveAutoZone();\n\n\t\t// smartdashboard values for drivetrain and elevator\n\t\tSmartDashboard.putData(\"Drive Train\", driveTrain);\n\n\t\tSmartDashboard.putData(\"Elevator\", elevatorFront);\n\t\tSmartDashboard.putData(\"Elevator\", elevatorRear);\n\n\t\t// instantiate the command used for the autonomous period\n\n\t}\n\n\t// established wait command for later use\n\tprivate void WaitCommmand(double d) {\n\n\t}\n\n\t// When Contact switches are pushed for at least 0.005 seconds, they will\n\t// show up as Pressed on SmartDashboard.\n\t\n//\tpublic void reduceSpeedButt() {\n//\t\tif (reduceSpeedButt.get() == true){\n//\t\t\tWaitCommmand(0.005);\n//\t\t\tx = .5 * x;\n//\t\t\ty = .5 * y;\n//\t\t\ttwist = .5 * twist;\n//\t\t\tdriveTrain.driveFieldOriented(x, y, twist);\n//\t\t}\n//\t}\n\n\t\n\t\n\tpublic void contactSwitchOne() {\n\t\tif (contactSwitchOne.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch One Pressed\",\n\t\t\t\t\tcontactSwitchOne.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchTwo() {\n\t\tif (contactSwitchTwo.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch Two Pressed\",\n\t\t\t\t\tcontactSwitchTwo.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchThree() {\n\t\tif (contactSwitchThree.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Limit Switch Three Pressed\",\n\t\t\t\t\tcontactSwitchThree.get());\n\t\t}\n\t}\n\n\tpublic void contactSwitchFour() {\n\t\tif (contactSwitchFour.get() == true) {\n\t\t\tWaitCommmand(0.005);\n\t\t\tSmartDashboard.putBoolean(\"Contact Switch Four Pressed\",\n\t\t\t\t\tcontactSwitchFour.get());\n\t\t}\n\t}\n\n\t// made it so Contact Switches would return true when pressed\n\tprotected boolean contactSwitchOneReturnTrue() {\n\t\tif (contactSwitchOne.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchTwoReturnTrue() {\n\t\tif (contactSwitchTwo.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchThreeReturnTrue() {\n\t\tif (contactSwitchThree.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprotected boolean contactSwitchFourReturnTrue() {\n\t\tif (contactSwitchFour.get() == true) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// TODO figure out what this is so we can write a better comment\n\tpublic void disabledPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\t// schedule the autonomous command (example)\n\tpublic void autonomousInit() {\n\t\tif (autoncommand != null) {\n\t\t\tautoncommand.start();\n\t\t}\n\n\t}\n\n\t/**\n\t * This function is called periodically during autonomous\n\t */\n\tpublic void autonomousPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\tpublic void teleopInit() {\n\t\t// This makes sure that the autonomous stops running when\n\t\t// teleop starts running. If you want the autonomous to\n\t\t// continue until interrupted by another command, remove\n\t\t// this line or comment it out.\n\n\t}\n\n\t/**\n\t * This function is called when the disabled button is hit. You can use it\n\t * to reset subsystems before shutting down.\n\t */\n\tpublic void disabledInit() {\n\n\t}\n\n\t/**\n\t * This function is called periodically during operator control\n\t */\n\tpublic void teleopPeriodic() {\n\t\tScheduler.getInstance().run();\n\t}\n\n\t/**\n\t * This function is called periodically during test mode\n\t */\n\tpublic void testPeriodic() {\n\t\tLiveWindow.run();\n\t}\n}\n"},"message":{"kind":"string","value":"Changed Elevator Names for SmartDashboard\n"},"old_file":{"kind":"string","value":"src/org/usfirst/frc/team2399/robot/Robot.java"},"subject":{"kind":"string","value":"Changed Elevator Names for SmartDashboard"}}},{"rowIdx":145833,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"a0047cc1f82e099effbbb04bd6049e7e460b2381"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"tariq1890/tacoco,tariq1890/tacoco,tariq1890/tacoco,spideruci/tacoco,tariq1890/tacoco,spideruci/tacoco"},"new_contents":{"kind":"string","value":"package org.spideruci.tacoco;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.FileVisitResult;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.SimpleFileVisitor;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.util.ArrayList;\n\nimport org.junit.runner.JUnitCore;\n\n\npublic final class TacocoRunner\n{\n\tpublic static void main(String[] args)\n\t{\n//\t\tint sleepLength = 2000;\n//\t\tSystem.out.println(\"Testing Thread.sleep()\");\n//\t\tSystem.out.println(\"Going to sleep for \"+sleepLength+\" ms.\");\n//\t\ttry\n//\t\t{\n//\t\t\tThread.sleep(sleepLength);\n//\t\t}\n//\t\tcatch(InterruptedException e)\n//\t\t{\n//\t\t\tSystem.out.println(e.getMessage());\n//\t\t}\n//\t\tSystem.out.println(\"Done sleeping.\");\n\t\t\n\t\ttry {\n\t\t\taddPath(args[0]);\n\t\t} catch (Exception e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\tJUnitCore core = new JUnitCore();\n\t\tcore.addListener(new TacocoListener());\n\n\t\tfor(String testClass : getClasses(args[0])){\n\t\t\ttry {\n\t\t\t\tcore.run(Class.forName(testClass));\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tSystem.out.println(System.getProperty(\"java.class.path\"));\n\t}\n\n\tpublic static void addPath(String s) throws Exception {\n\t File f = new File(s);\n\t URI u = f.toURI();\n\t URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();\n\t Class urlClass = URLClassLoader.class;\n\t Method method = urlClass.getDeclaredMethod(\"addURL\", new Class[]{URL.class});\n\t method.setAccessible(true);\n\t method.invoke(urlClassLoader, new Object[]{u.toURL()});\n\t}\n\n\tpublic static ArrayList getClasses(final String p){\t\t\n\t\tfinal ArrayList ret = new ArrayList();\n\t\t\n\t\ttry {\n\t\t\tFiles.walkFileTree(Paths.get(p), new SimpleFileVisitor() {\n\t\t\t @Override\n\t\t\t public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t String str = file.toString();\n\t\t\t if(str.endsWith(\".class\") && !str.matches(\"(.*)\\\\$(.*)\")) {\n\t\t\t \tSystem.out.println(str.replaceAll(p.endsWith(\"/\")?p:p+\"/\",\"\").replace('/','.').replaceAll(\"\\\\.class\",\"\")); \n\t\t\t \tret.add(str.replaceAll(p.endsWith(\"/\")?p:p+\"/\",\"\").replace('/','.').replaceAll(\"\\\\.class\",\"\"));\n\t\t\t }\n\t\t\t return FileVisitResult.CONTINUE;\n\t\t\t }\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn ret;\n\t}\t\t\t\n\n}\n"},"new_file":{"kind":"string","value":"src/main/java/org/spideruci/tacoco/TacocoRunner.java"},"old_contents":{"kind":"string","value":"package org.spideruci.tacoco;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.net.URI;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.FileVisitResult;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.SimpleFileVisitor;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.util.ArrayList;\n\nimport org.junit.runner.JUnitCore;\n\n\npublic final class TacocoRunner\n{\n\tpublic static void main(String[] args)\n\t{\n//\t\tint sleepLength = 2000;\n//\t\tSystem.out.println(\"Testing Thread.sleep()\");\n//\t\tSystem.out.println(\"Going to sleep for \"+sleepLength+\" ms.\");\n//\t\ttry\n//\t\t{\n//\t\t\tThread.sleep(sleepLength);\n//\t\t}\n//\t\tcatch(InterruptedException e)\n//\t\t{\n//\t\t\tSystem.out.println(e.getMessage());\n//\t\t}\n//\t\tSystem.out.println(\"Done sleeping.\");\n\t\t\n\t\ttry {\n\t\t\taddPath(args[0]);\n\t\t} catch (Exception e1) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te1.printStackTrace();\n\t\t}\n\t\tJUnitCore core = new JUnitCore();\n\t\tcore.addListener(new TacocoListener());\n\n\t\tfor(String testClass : getClasses(args[0])){\n\t\t\ttry {\n\t\t\t\tcore.run(Class.forName(testClass));\n\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t}\n\t\t\n\t\tSystem.out.println(System.getProperty(\"java.class.path\"));\n\t}\n\n\tpublic static void addPath(String s) throws Exception {\n\t File f = new File(s);\n\t URI u = f.toURI();\n\t URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();\n\t Class urlClass = URLClassLoader.class;\n\t Method method = urlClass.getDeclaredMethod(\"addURL\", new Class[]{URL.class});\n\t method.setAccessible(true);\n\t method.invoke(urlClassLoader, new Object[]{u.toURL()});\n\t}\n\n\tpublic static ArrayList getClasses(final String p){\t\t\n\t\tfinal ArrayList ret = new ArrayList();\n\t\t\n\t\ttry {\n\t\t\tFiles.walkFileTree(Paths.get(p), new SimpleFileVisitor() {\n\t\t\t @Override\n\t\t\t public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n\t\t\t String str = file.toString();\n\t\t\t if(str.endsWith(\".class\") && !str.matches(\"(.*)\\\\$(.*)\")) {\n\t\t\t \tSystem.out.println(str.replaceAll(p.endsWith(\"/\")?p:p+\"/\",\"\").replace('/','.').replaceAll(\"\\\\.class\",\"\")); \n\t\t\t \tret.add(str.replaceAll(p.endsWith(\"/\")?p:p+\"/\",\"\").replace('/','.').replaceAll(\"\\\\.class\",\"\"));\n\t\t\t }\n\t\t\t return FileVisitResult.CONTINUE;\n\t\t\t }\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn ret;\n\t}\t\t\t\n\n}\n"},"message":{"kind":"string","value":"bug fix\n"},"old_file":{"kind":"string","value":"src/main/java/org/spideruci/tacoco/TacocoRunner.java"},"subject":{"kind":"string","value":"bug fix"}}},{"rowIdx":145834,"cells":{"lang":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"stderr":{"kind":"string","value":""},"commit":{"kind":"string","value":"368c8a894a4b7031a21f1c6a7541fa2627be88f8"},"returncode":{"kind":"number","value":0,"string":"0"},"repos":{"kind":"string","value":"university-information-system/uis,university-information-system/uis,university-information-system/uis,university-information-system/uis"},"new_contents":{"kind":"string","value":"package at.ac.tuwien.inso.service;\n\nimport at.ac.tuwien.inso.entity.*;\n\nimport org.springframework.security.access.prepost.PreAuthorize;\n\nimport java.util.*;\n\npublic interface StudyPlanService {\n\n\t/**\n\t * creates a new study plan\n\t * may throw a ValidationException if study plans name, or optional, mandatory or freechoice ects values are null or empty or <=0\n\t *\n\t * @param studyPlan\n\t * @return\n\t */\n @PreAuthorize(\"hasRole('ADMIN')\")\n StudyPlan create(StudyPlan studyPlan);\n\n /**\n * returns a list of all StudyPlans.\n * user must be authorized\n * @return\n */\n @PreAuthorize(\"isAuthenticated()\")\n List findAll();\n\n /**\n * returns the StudyPlan with the corresponding id\n * may throw a BusinessObjectNotFoundException if there is no StudyPlan with this id\n * @param id should not be null and not <1\n * @return\n */\n @PreAuthorize(\"isAuthenticated()\")\n StudyPlan findOne(Long id);\n\n /**\n * try to find all SubjectsForStudyPlan by a study plan id.\n * should be ordered by semester recommendation\n * user must be authorized\n * \n * @param id. should not be null and not <1\n * @return\n */\n @PreAuthorize(\"isAuthenticated()\")\n List getSubjectsForStudyPlan(Long id);\n\n /**\n * \n * returns a list of grades for the subjects for the CURRENTLY LOGGED IN STUDENT.\n * user needs to be authenticated\n * @param id. should not be null and not <1\n * @return\n */\n @PreAuthorize(\"isAuthenticated()\")\n List